nginx反向代理文件夹

avi*_*nat 4 nginx reverse-proxy

我正在尝试使用反向代理访问另一个服务器后面的服务器。“主”服务器位于 mydomain.com 后面,我想使用 mydomain.com/test 访问第二个服务器。目前只有 mydomain.com/test 有效。

但是,如果我尝试访问 mydomain.com/test/myfiles,我将被重定向到不存在的 mydomain.com/myfiles,因为此 url 以“主”服务器为目标,因此出现 404 not found。我用proxy_redirect尝试了多种方法,重写但没有任何效果。

server {
    listen   80;
    index index.php index.html index.htm;
    root /path/to/content;
    server_name localhost mydomain.com;

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

    location /test/ {
        proxy_pass http://192.168.1.202/;
        proxy_set_header Host $host;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}
Run Code Online (Sandbox Code Playgroud)

curl -I "http://192.168.1.202" -H "Host: mydomain.com" 在主服务器上给出:

HTTP/1.1 301 Moved Permanently
Server: nginx/1.2.1
Date: Sun, 02 Nov 2014 15:02:56 GMT
Content-Type: text/html
Content-Length: 184
Location: example.com/myfiles
Connection: keep-alive
Run Code Online (Sandbox Code Playgroud)

Xav*_*cas 6

问题是,当您在proxy_pass指令中使用尾部斜杠时,默认行为proxy_redirect如下:

location /test/ {
    proxy_pass http://192.168.1.202/;
    proxy_set_header Host $host;
}
Run Code Online (Sandbox Code Playgroud)

是相同的 :

location /test/ {
    proxy_pass http://192.168.1.202/;
    proxy_redirect http://192.168.1.202/ /test/;
    proxy_set_header Host $host;
}
Run Code Online (Sandbox Code Playgroud)

因此,鉴于 curl 输出,您必须进行设置:

location /test/ {
    proxy_pass http://192.168.1.202/;
    proxy_redirect http://$host/ /test/;
    proxy_set_header Host $host;
}
Run Code Online (Sandbox Code Playgroud)