Home > Software engineering >  How redirect partial uri in nginx to another app?
How redirect partial uri in nginx to another app?

Time:12-31

In my server with nginx with Certbot I have two api running, in port 5000 and 3001.

All requests are for the app on port 5000, but when i request it in the 'pdf-generator' uri I want to send to the app on port 3001

Examples:

  • my-domain/abc -> localhost:5000
  • my-domain/pdf-generator -> localhost:3001
  • my-domain/pdf-generator/about -> localhost:3001/about
  • my-domain/pdf-generator/abc-> localhost:3001/abc

I searched in several places, I saw some similar situations but I didn't get success

tried:

    location = /pdf-generator/ {
        proxy_pass    http://localhost:3001;
    }
    location /pdf-generator {
        proxy_pass    http://localhost:3001$request_uri;
    }
    location = /pdf-generator/ {
        proxy_pass    http://localhost:3001/$request_uri;
    }
    location /pdf-generator {
        rewrite /pdf-generator/(.*) /$1  break;
        proxy_pass    http://localhost:3001;
    }
    location /pdf-generator {
        rewrite /pdf-generator/(.*) /$1  break;
        proxy_pass    http://localhost:3001/;
    }

Accessing the app's port 3001 directly through the server's IP in the uri "about" appears correctly what I need, but I would like to do it through my domain in the uri "pdf-generator"

  • myip:3001/about -> "ok"
  • my-domain/pdf-generator/about -> needs to show "ok"

My nginx sites-avaiable config

server {
    server_name   my-domain;

    location / {
        proxy_pass         http://localhost:5001;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }

    location /pdf-generator {
        rewrite ^/pdf-generator(/|$)(.*) /$2 break;
        proxy_pass    http://localhost:3001;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-domain/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-domain/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

server {
    if ($host = my-domain) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen        80;
    server_name   my-domain;
    return 404; # managed by Certbot
}

CodePudding user response:

You can do it like this:

    location /pdf-generator {
        rewrite ^/pdf-generator(/|$)(.*) /$2/ break;
        proxy_pass    http://localhost:3001;
    }
    location / {
        proxy_pass    http://localhost:5000;
    }
  • Related