I have an Nginx that redirects to several different web servers based on URL path after host.

My Nginx host is nginx.main.com

current redirect rules are

 # Redirects for Math     
     location ~ ^/(math)($|/) {
     proxy_pass  http://www.aaa.com:8081;
     include /etc/nginx/proxy.conf;
     break;   }

  # Redirects for CS  
     location ~ ^/(cs)($|/) {
     proxy_pass  http://www.aaa.com:8082;
     include /etc/nginx/proxy.conf;
     break;   }

This causes

http://nginx.main.com/math/index.html to be redirected to http://www.aaa.com:8081/math/index.html


http://nginx.main.com/cs/index.html to be redirected to http://www.aaa.com:8082/cs/index.html

(My 2 aaa sites sit on IIS on two different ports and 2 different base dirs)

Because of IIS restrictions I dont want the '/math/' and '/cs/' to be added to the destination URL.

e.g., I want

http://nginx.main.com/math/index.htm to be redirected to http://www.aaa.com:8081/index.html

Is this possible with Nginx ?

  • Do you misuse word redirect instead of (reverse) proxy? – Alexey Ten Jun 11 '14 at 12:53

This should work, if I understand you question correctly

location /math/ {
    proxy_pass  http://www.aaa.com:8081/;
    include /etc/nginx/proxy.conf;

location /cs/ {
    proxy_pass  http://www.aaa.com:8082/;
    include /etc/nginx/proxy.conf;

I see no reason to use regexp locations, so I changed them to simple. Also break directive does nothing in this config.

I've added trailing slash to proxy_pass so nginx replaces location prefix with this slash and result is http://nginx.main.com/cs/index.html proxied to http://www.aaa.com:8082/index.html.

  • This didn't work, it still passes the /cs or /math to the destination web server. I found that using "rewrite ^/math(.*)$ $1 break;" will do the trick though ! – thedrs Jun 17 '14 at 15:36
  • One more problem that arose after using rewrite... Any root resource that is accessed from the destination site (e.g., /scripts/foo.js) ruins the whole proxy scheme here because it will try to access nginx.main.com/scripts.foo.js which obviously does not exist. So the only solution left is to use vhosts with their own DNS (e.g., math.main.com and cs.main.com) :P – thedrs Jun 17 '14 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.