Nginx subdomain proxypass

nginxreverse-proxysubdomain

I want to redirect non-ssl traffic to ssl for all subdomains. I want to keep the subdomain the same. I want to specify a different proxy_pass for staging.foo.com. I only have 3 things going right now foo.com, www.foo.com and staging.foo.com. I want to proxy pass the bare domain and the www to localhost 8000. And proxy pass the staging subdomain to localhost 8001.

http://foo.com/ -> https://foo.com/ -proxy-> 127.0.0.1:8000
http://www.foo.com/ -> https://www.foo.com/ -proxy-> 127.0.0.1:8000
http://staging.foo.com/ -> https://staging.foo.com/ -proxy-> 127.0.0.1:8001

With the following, it looks like all traffic to www or staging gets redirected to the bare domain. What am I doing wrong?

server {
        listen 80;
        server_name foo.com www.foo.com staging.foo.com;
        rewrite ^ https://$server_name$request_uri? permanent;
}
server {
        listen 443;
        server_name foo.com www.foo.com;
        # ...
        location / {
          proxy_pass    http://127.0.0.1:8000/;
          # ...
        }
}
server {
        listen 443;
        server_name staging.foo.com;
        # ...
        location / {
          proxy_pass    http://127.0.0.1:8001/;
          # ...
        }
}

Best Answer

Change first server {} section to:

server {
        listen 80;
        server_name foo.com www.foo.com staging.foo.com;
        return 301 https://$host$request_uri;
}

Note $server_name --> $host, this is a solution of your problem. Replacement of redirect to return is not necessary, but much better.