Search code examples
url-rewritingnginx-reverse-proxyurl-parametersproxypass

How do I use NGINX as a reverse proxy, passing query string parameters for my specific use case


I have the NGINX config shown below.

  upstream api {
     ...
  }

server {

  listen 2023; 

  server_name www.server.com;

  location /api/v1/comment/ {

    rewrite /api/v1/comment(.*) /api/v1/comment$1 break;
    proxy_pass http://api/;

  }

The following path combinations work and return data from the upstream API but the top two have the extra trailing slash that is not ideal:

  • api/v1/comment/?foo=1234
  • api/v1/comment/
  • api/v1/comment/1

I would like the following path combinations to work instead:

  • api/v1/comment?foo=1234 (instead of api/v1/comment/?foo=1234)
  • api/v1/comment (instead of api/v1/comment/)
  • api/v1/comment/1 (works now - this is desired)

I have struggled to get this working as-is and am wondering if any great stackoverflowers can help a guy out with a boost in figuring out what I am trying to accomplish. Most answers I have tried online have not worked and this is the first thing I have landed on that works.... sort of... for the purpose.

Thank you!


Solution

  • I cant believe I didn't see it before...

    Instead of keeping /comment/ as a part of the location and /comment in the rewrite command:

     upstream api {
         ...
      }
    
    server {
    
      listen 2023; 
    
      server_name www.server.com;
    
      location /api/v1/comment/ {
    
        rewrite /api/v1/comment(.*) /api/v1/comment$1 break;
        proxy_pass http://api/;
    
      }

    I removed /comment/ from the location and /comment from the rewrite command:

     upstream api {
         ...
      }
    
    server {
    
      listen 2023; 
    
      server_name www.server.com;
    
      location /api/v1/ {
    
        rewrite /api/v1(.*) /api/v1$1 break;
        proxy_pass http://api/;
    
      }

    This made it so I didn't have to use the extra / when reaching out to the reverse proxy to make the communication to the API work.