eat-sleep-code
eat-sleep-code

Reputation: 4855

nginx proxy requests for a specific path

Is it possible to pass requests for a specific path to a different upstream server?

Here is my nginx site configuration:

upstream example.org {
    server 127.0.0.1:8070;
    keepalive 8;
}

server {
    listen 0.0.0.0:80;
    server_name example.org www.example.org;
    access_log /var/log/nginx/example.org.log;

    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://example.org;
      proxy_redirect off;
    }
 }

Currently, requests to this site are redirected to a Node.js instance running on port 8070.

I would like requests to this site that have a path starting with /services to be redirected to another Node.js instance running on port 8080.

Is this possible? And of course -- how so?

Upvotes: 5

Views: 11349

Answers (1)

severin
severin

Reputation: 10268

Yes, just add another location block:

upstream example.org {
    server 127.0.0.1:8070;
    keepalive 8;
}
upstream other.example.org {
    server 127.0.0.1:8080;
    keepalive 8;
}

server {
    listen 0.0.0.0:80;
    server_name example.org www.example.org;
    access_log /var/log/nginx/example.org.log;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_redirect off;

    location / {
      proxy_pass http://example.org;
    }

    location /services {
      proxy_pass http://other.example.org;
    }
 }

Note: I extracted all shared proxy directives into the server block so that they are not repeated in each location block. If they would differ between different locations, you would have to move them again into the location blocks...

Upvotes: 3

Related Questions