Nginx – How to Append Query Parameter to a React Application

nginxquerystringrewrite

I am a beginner in Nginx and I want to append a query parameter to the URL (for instance myid) in order to serve a react application. I am using nginx/1.18.0 (Ubuntu)

There are similar questions like:

Appending query parameters to specific URI

But I cannot find a solution to the problem.

React usually creates static content, so using a "try_files" element (pointing to /index.html) seems logical.

Here is the configuration file

server {
  listen 9999 ssl default_server;
  listen [::]:9999 ssl default_server;

  ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    
  ssl_certificate        /keystores/mycert.crt.pem;         ## 
  ssl_certificate_key    /keystores/mycert.key.pem;         ## 
  ssl_client_certificate /keystores/.npm.certs.pem;         ## CA Bundle
  ssl_verify_client on;

  root /home/edu/my-react-app;

  index index.html;

  server_name _;
  error_log /home/edu/log/nginx_log debug;

  #Append query param (trying different flags)
  rewrite ^(/login)$ $1?myid=LAST last;
  #rewrite ^(/login)$ $1?myid=NO_FLAG ;
  #rewrite ^(/login)$ $1?myid=BREAK break;
  #rewrite ^(/login)$ $1?myid=REDIRECT redirect;
  #rewrite ^(/login)$ $1?myid=PERMANENT permanent;


  location / {
    try_files $uri $uri/  /index.html =404; # Redirect to index.html of the "static" react application!!!
  }
}

I have tried all 5 flag rewrite options with these results:

no-flag, last, and break flags: In the log file, it states that a query parameter has been added to the URL but the new URL does not appear in the browser address bar, and the application cannot find this query param.

redirect and permanent flags: In the log file, it states that the query parameter has been added to the URL MANY TIMES and the new URL appears (with the query parameter repeated many times) in the browser address bar, but the browser complains as it has been redirected many times.

Putting the "rewrite" statement into the "location" statement doesn't work.

Any ideas?
Thanks

Best Answer

If you want React to see the query parameter you will need to use redirect or permanent. The other modes of rewrite are internal to Nginx. See the rewrite documentation.

To protect against a redirection loop, you will need to wrap the rewrite...redirect within an if block. For example:

location / {
    try_files $uri $uri/ /index.html =404;
}
location = /login {
    if ($arg_myid = "") {
        rewrite ^ /login?myid=xxx redirect;
    }
    try_files /index.html =404;
}

See this caution on the use of if within a location block.