Nginx per location / pass rewriten uri to proxy_pass

lowk3y picture lowk3y · Dec 9, 2012 · Viewed 31.9k times · Source

What the quickest and cleanest solution if you want to proxy URL request to two different backends via proxypass based on location.

location /app1/ {
    alias /var/www/ruby/public;
    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_redirect    off;
    try_files $uri $uri/ @ruby;
}

location @ruby {
    proxy_pass http://127.0.0.1:3000;
}

location /app2/ {
    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_redirect    off;
    try_files $uri $uri/ @other;
}

location @other {
    proxy_pass http://127.0.0.1:8080;
}

With this config nginx pass "/app1" or "/app2" to proxy and backend doesn't recognize the url/command ..

as for instance would like to pass to http://127.0.0.1:3000 only /messages when accessing http://<nginx>/app1/messages - but in configuration above also pass /app1/ as http://127.0.0.1:3000/app1/messages. Same goes for /app2

Answer

user1916656 picture user1916656 · Dec 19, 2012

Try putting "/" at the end of upstream name e.g

proxy_pass http://127.0.0.1:8080/;

Please see this post: How to preserve request url with nginx proxy_pass