bswinnerton
bswinnerton

Reputation: 4721

Routing to different servers with nginx

Is there a way to use nginx as a router while keeping the requested domain in the URL? For example, if I hit mysite.com, the nginx routing server looks at the URL and directs traffic to a particular server, all while maintaining the original requested domain in the URL.

E.g.

mysite.com/site1/params
Router -> site1.mysite.com/params

But even though behind the scenes site1.mysite.com/params is being called, the user sees mysite.com/site1/params in the URL.

I've taken a stab at the configuration, but seem to be getting 404's.

upstream site1 {
  server site1.mysite.com;
}

location /site1 {
  rewrite ^(.*)$ /$1 break;
  proxy_pass  http://site1;
  proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
  proxy_redirect off;
  proxy_buffering off;
  proxy_set_header        Host            $host;
  proxy_set_header        X-Real-IP       $remote_addr;
  proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
}

Upvotes: 5

Views: 5133

Answers (1)

Alexey Ten
Alexey Ten

Reputation: 14344

Use location with trailing slash, remove rewrite and use proxy_pass with / uri. Nginx will take of replacing /site1/ with /. Also, you may need to set Host header to site1.mysite.com not the $host.

location /site1/ {
  proxy_pass  http://site1/;
  proxy_set_header Host site1.mysite.com;
  ...
}

Upvotes: 1

Related Questions