Monday, December 29, 2014

Nginx reverse proxy + URL rewrite



Nginx is running on port 80, and I'm using it to reverse proxy URLs with path /foo to port 3200 this way:



location /foo {

proxy_pass http://localhost:3200;
proxy_redirect off;
proxy_set_header Host $host;
}


This works fine, but I have an application on port 3200, for which I don't want the initial /foo to be sent to. That is - when I access http://localhost/foo/bar, I want only /bar to be the path as received by the app. So I tried adding this line to the location block above:



rewrite ^(.*)foo(.*)$ http://localhost:3200/$2 permanent;



This causes 302 redirect (change in URL), but I want 301. What should I do?


Answer



Any redirect to localhost doesn't make sense from a remote system (e.g. client's Web browser). So the rewrite flags permanent (301) or redirect (302) are not usable in your case.



Please try following setup using a transparent rewrite rule:



location  /foo {
rewrite /foo/(.*) /$1 break;
proxy_pass http://localhost:3200;

proxy_redirect off;
proxy_set_header Host $host;
}


Use curl -i to test your rewrites. A very subtle change to the rule can cause nginx to perform a redirect.


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...