Nginx – How to use Nginx to both rewrite and proxy_pass whilst keeping the user-entered URL

nginxproxypassrewrite

I'm a beginner Nginx user trying to proxy the following:

http://subdomain.example.com/mypage/login
TO
http://some_ip_address/login

(not just /login – the site has other contexts too e.g. /static, /api, etc.)

Whilst I can functionally make this work, the user sees http://some_ip_address in their browser, which I'd like to avoid.

That config looks like this:

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile      on;
    keepalive_timeout  3;
    server {
        server_name this_server_ip;
        location /mypage/ {
            proxy_pass http://some_ip_address;
            rewrite ^/mypage/(.*)$ http://some_ip_address/$1 last;
        }
        location / {
          root /var/local/directory/;
        }
    }
}

To try to fix it, I've tried combinations of:

  • proxy_pass http://some_ip_address/; (i.e. with trailing slash)
  • proxy_set_header Host $host;
  • rewrite ^/mypage/(.*)$ /$1 last;

But I either get 404's or serve up the page that's hosted at http://subdomain.example.com, i.e. rewrite works but proxy_pass doesn't.

There are a few similar questions on serverfault but none seem to address my particular flavour of this problem, unfortunately. Examples are this one and that one.

Any suggestions would be very much appreciated, thank you.

Best Answer

You are specifying this_server_ip as the hostname for this virtualhost. That means that this virtualhost isn't used for any requests that have a domain name, but your nginx default virtual server is used for requests for http://subdomain.example.com/.

You need to change your server_name to subdomain.example.com, or add default_server to the listen directive on this server block and remove it from the nginx default configuration.

EDIT: Try this vhost configuration:

server {
    server_name subdomain.example.com;
    location ~ /(mypage|static/api)/ {
        proxy_pass http://some_ip_address/$1/;
    }
    location / {
      root /var/local/directory/;
    }
}

That is, you don't need a rewrite statement at all, because you are proxying the request to another server.