Nginx Proxy/Upstream redirects use wrong port and protocol

httpsnginxPROXYrewrite

I am using an NGINX server as an ssl proxy for some other NGINX servers.
Unforntunately if a request is redirected by an upstream server, the location field contains the wrong destination port.

curl -v "https://example.com/site":

> GET /site HTTP/2
> Host: example.com
> User-Agent: curl/7.58.0
> Accept: */*
> 
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 301 
< server: nginx
< date: Sun, 18 Mar 2018 20:01:44 GMT
< content-type: text/html
< content-length: 178
< location: http://example.com:9101/site/
< strict-transport-security: max-age=15768000; includeSubDomains

NGINX Proxy:

# Proxy: example.com
####################

server {
  listen 0.0.0.0:80;
  listen [::]:80;
  server_name example.com;
  root /srv/www/_empty;
  location / { return 301 https://example.com$request_uri; }
}

upstream myupstream {
  server [::1]:9101;
}

server {
  listen 0.0.0.0:443 ssl http2;
  listen [::]:443 ssl http2;
  server_name example.com;
  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
  root /srv/www/_empty;

  location / {

    proxy_set_header    Host                   $http_host;
    proxy_set_header    X-Real-IP              $remote_addr;
    proxy_set_header    X-Forwarded-For        $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Proto      $scheme;
    proxy_set_header    X-Frame-Options        "";
    proxy_set_header    X-Content-Type-Options "";
    proxy_pass          http://myupstream;
  }
}

NGINX Upstream Server:

# NGINX Site: example.com
#########################

server {
  # Server
  listen [::1]:9101;
  server_name example.com;

  # Root
  root /srv/www/example.com/staging;

  # Disable Caching
  sendfile off;

  # Charset
  charset utf-8;

  # Default
  location / {
    index index.html;
    try_files $uri $uri/ =404;
  }
}

Both NGINX instances running as seperate master processes on the same machine. Anything else works perfectly.

I thought, that NGINX Proxy would rewrite the upstream response so it converts http://example.com:9001/site/ to https://example.com/site/.

What did I forgot?

Best Answer

proxy_redirect default will not work the way you expect because you are using an upstream block and nginx cannot get the required string from the proxy_pass statement. You can specify it explicitly with:

proxy_redirect http://example.com:9101/ /;

See this document for more.


Alternatively, tell your upstream server to stop specifying a port in its redirection responses with:

port_in_redirect off;

See this document for more.