nginx proxy pass redirects ignore port

Solution 1:

I just had to solve the same problem with Jenkins running behind nginx. What did it for me was to include the server port into the Host header that's being sent to Jenkins:

proxy_set_header Host $host:$server_port;

Hope that helps.

Solution 2:

The problem is that the Node.js application is not issuing the redirect correctly. You may be able to use proxy_redirect to correct this in nginx:

proxy_redirect http://localhost/ http://localhost:8080/;

Solution 3:

Per the conversation on this question, the proper resolution is to adjust the proxy's Host header directive.

Change this:

proxy_set_header Host $host;

To this:

proxy_set_header Host $http_host;

$http_host holds the value as specified in HTTP HOST header, which includes the port. Redirects should pick up the custom port without further customization to OP's setup.

These answers (same ticket) elaborate further:

  • https://serverfault.com/a/407983/298623
  • https://serverfault.com/a/731985/298623

Solution 4:

I tried the above solutions, but they all failed whenever the node application issued a fully qualified URL in the location header, such as "http://nodeapp.com:8080/new/location"

So I wound up using the $http_host to pass host and port. And using a match ~^ to rewrite the urls entirely.

  proxy_pass http://10.0.0.3:8080;

  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header Host $http_host;

  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

  proxy_redirect default;
  proxy_redirect ~^(https?://[^:]+):\d+(?<relpath>/.+)$ http://10.0.0.3:8000$relpath;

In our case, the Node server is running on 8080, and our nginx proxy is running on 8000. This means that every fully qualified URL in a location header needs to be re-written. Hope this helps someone !!

Tags:

Nginx