Nginx 代理/上游重定向使用错误的端口和协议

alu*_*ter 5 rewrite nginx proxy https

我使用 NGINX 服务器作为其他一些 NGINX 服务器的 ssl 代理。不幸的是,如果请求被上游服务器重定向,则位置字段包含错误的目标端口。

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
Run Code Online (Sandbox Code Playgroud)

NGINX 代理:

# 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

NGINX 上游服务器:

# 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

两个 NGINX 实例在同一台计算机上作为单独的主进程运行。其他一切都完美。

我认为 NGINX 代理会重写上游响应,以便将其转换http://example.com:9001/site/https://example.com/site/.

我忘记了什么?

Ric*_*ith 3

proxy_redirect default将无法按您期望的方式工作,因为您正在使用upstream块并且nginx无法从语句中获取所需的字符串proxy_pass。您可以使用以下方式显式指定它:

proxy_redirect http://example.com:9101/ /;
Run Code Online (Sandbox Code Playgroud)

请参阅此文档了解更多信息。


或者,告诉您的上游服务器停止在其重定向响应中指定端口:

port_in_redirect off;
Run Code Online (Sandbox Code Playgroud)

请参阅此文档了解更多信息。