Nginx proxy_pass 仅部分工作

Dro*_*dOS 2 reverse-proxy nginx php-7

我有以下设置

  • 主服务器 - 调用它 https://master.com
  • 从服务器 - 调用它 https://slave.com

两者都在 Ubuntu 16.04 上运行 Nginx

在主服务器上,我在我的/etc/nginx/sites-available/default文件中创建了以下配置块

location /test
{
 rewrite ^/test(.*) /$1 break;
 proxy_pass https://slave.com;
 proxy_read_timeout 240;
 proxy_redirect off;
 proxy_buffering off;
 proxy_set_header Host $host;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto https;
}
Run Code Online (Sandbox Code Playgroud)

一个service nginx reload以后master.com,我可以做以下

  • 浏览https://master.com/test并查看来自 的输出slave.com\index.php
  • 浏览https://master.com/test/test.txt并查看文件中的文本slave.com\test.txt
  • 浏览https://master/com/test/test.jpg并查看文件中的图像slave.com\test.jpg

但是,我不能执行以下任何操作

  • 浏览到https://master.com/test/test.php哪个而不是向我显示输出,而是向我https://slave.com/test.php显示 404 错误消息
  • 浏览到https://master.com/test/adminer/adminer.php其中,而不是向我展示了Adminer实例的登录屏幕上的奴隶,https://slave.com/adminer/adminer.php显示我要在Adminer实例的登录屏幕master.comhttps://master.com/adminer/adminer.php

这显然是因为我在master.com. 但是,我无法看到那可能是什么。

为了完整起见,这是我在两台服务器上的配置:

Ubuntu - 16.04.3 Nginx - 1.10.3 PHP - 7.0.22

我应该解释为什么^~需要 ,因为这从我最初的问题中不清楚。我有另一个块设置来处理 .php 上的 PHP 脚本master.com

location ~ \.php$ 
{
 try_files $uri =404;
 fastcgi_split_path_info ^(.+\.php)(/.+)$;
 fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
 fastcgi_index index.php;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 include fastcgi_params;
}
Run Code Online (Sandbox Code Playgroud)

由于 Nginx 处理这些指令的方式,这个块在处理.php文件时优先,并master.com最终在本地查找.php实际运行的脚本slave.com。避免这种情况的唯一方法是使用^~

Tar*_*ani 8

你的做法是错误的。在处理/test您重写它并将其发送出块的块内。在proxy_pass实际上从未发生,因为新的URL没有/test在里面。解决方法很简单,不要用rewrite

location /test/
{
 proxy_pass https://slave.com/;
 proxy_read_timeout 240;
 proxy_redirect off;
 proxy_buffering off;
 proxy_set_header Host $host;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto https;
}
Run Code Online (Sandbox Code Playgroud)

附加/在位置路径的末尾,并且proxy_pass服务器将确保将后面的/test/内容发送到您的proxy_pass地址

编辑-1

这是我在发布此答案之前设置的示例测试用例。

events {
    worker_connections  1024;
}
http {
server {
   listen 80;

   location /test1 {
     proxy_pass http://127.0.0.1:81;
   }

   location /test2 {
     proxy_pass http://127.0.0.1:81/;
   }

   location /test3/ {
     proxy_pass http://127.0.0.1:81;
   }

   location /test4/ {
     proxy_pass http://127.0.0.1:81/;
   }

}

server {
   listen 81;

   location / {
     echo "$request_uri";
   }
}
}
Run Code Online (Sandbox Code Playgroud)

现在结果解释了所有 4 个位置块之间的差异

$ curl http://192.168.33.100/test1/abc/test
/test1/abc/test

$ curl http://192.168.33.100/test2/abc/test
//abc/test

$ curl http://192.168.33.100/test3/abc/test
/test3/abc/test

$ curl http://192.168.33.100/test4/abc/test
/abc/test
Run Code Online (Sandbox Code Playgroud)

正如您在/test4url 中看到的,代理服务器只能看到/abc/test