使用nginx反向代理进行redirect

我有ab域(例如),并希望在ab/c提供一些github页面( username.github.io/project )。 这意味着我也想保持我的浏览器url为ab/c并显示username.github.io/project内容。

我在nginx模块中有以下设置

 location /c { proxy_pass http://username.github.io/project; proxy_redirect http://username.github.io http://ab; 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_buffering off; } 

如果我更改proxy_set_header Host $http_hostproxy_set_header Host $proxy_host$host ,它只是redirect到http://username.github.io/project这不是我的意思。 我能怎么做?

只需通过删除 proxy_set_header Host $http_host行来将正确的主机proxy_set_header Host $http_host送到您的代理目标。

如果在您的服务器块中将abconfiguration为服务器名称,那么如果您在位置前缀和proxy_pass目标中使用了尾部斜线,则甚至不需要proxy_redirect指令,如文档中所述:

 Syntax: proxy_redirect default; proxy_redirect off; proxy_redirect redirect replacement; Default: proxy_redirect default; Context: http, server, location 

[…]

缺省参数指定的缺省replace使用location和proxy_pass指令的参数。 因此,下面的两个configuration是等价的:

 location /one/ { proxy_pass http://upstream:port/two/; proxy_redirect default; } location /one/ { proxy_pass http://upstream:port/two/; proxy_redirect http://upstream:port/two/ /one/; } 

[….]

所以,这应该做到这一点:

 server { server_name ab; location /c/ { proxy_pass http://username.github.io/project/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_buffering off; } } 

使用

 proxy_redirect off; 

所以你的设置将会是

 location /c { proxy_pass http://username.github.io/project; proxy_redirect http://username.github.io; proxy_set_header Host username.github.io; proxy_set_header X-Host username.github.io; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_buffering off; }