无法将 Nginx 设置为与 proxy_pass 一起处理 PHP

ank*_*981 6 nginx

我的 Nginx 设置有三个要求:

  1. 将 / 上的所有请求转发到在端口 9001 上运行的 Java 服务器
  2. 拦截所有静态文件 URL 并通过 Nginx 本身提供它们。
  3. 从包含 PHP 脚本的文件夹提供特定的基本 URL。

其中,我能够实现前两个,但是当我http://localhost/ecwid_fu_scripts/通过 Web 浏览器访问时,请求被运行在端口 9001 上的 Java 服务器拦截,并且不会路由到index.phpin /home/ankush/ecwid_fu_scripts/。这是我的 Nginx 配置:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _;

    location /assets/images/ {
        root /home/ankush/fu_main_files/;
        autoindex off;
        sendfile on; 
        tcp_nopush on; 
        tcp_nodelay on; 
        keepalive_timeout 100;
    }   

    location /ecwid_fu_scripts/ {
        index index.php;
        root /home/ankush/ecwid_fu_scripts/;
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }   

    location / { 
        proxy_pass http://localhost:9001;
    }   

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

Isk*_*kar 5

您的问题与root指令有关,以及 this 的范围root

location /ecwid_fu_scripts/ {
    root /home/ankush/ecwid_fu_scripts/;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,当有人请求 example.com/ecwid_fu_scripts/ 时,nginx 正在查找定义中的文件root以及位置。这变成了 /home/ankush/ecwid_fu_scripts/ecwid_fu_scripts/,这不是你的 index.php 所在的位置。

为了解决这个问题,您有两个选择(如果您对项目有自由,#2 是首选选项):

  1. root将该位置块的更改为 /home/ankush/。
  2. 或者重组您的项目结构,让所有内容都在一个相关的项目文件夹中。现在,将全局root——任何位置块之外的指令——设置为新的项目文件夹名称(比方说root /home/ankush/ecwid_files/;,在server_name指令之后)。

现在,我们仍然需要在location ~ \.php$块内添加块的内容location /ecwid_fu_scripts/,因为当root更改时,需要在同一个块中使用与这个新根相关的东西。这是因为这种类型的陷阱:ecwid_fu_scripts 的位置块说它是一个 .php 文件,它执行 try_files,然后它以这个块结束,并发送到下一个相关块: global location ~ \.php$。问题是,它不再知道是什么root,因为它不是全局定义的。因此,此块中的 fastcgi_pass 未获得完整路径。

所以最后,您的配置将与选项 #1 类似:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _;

    location /assets/images/ {
        root /home/ankush/fu_main_files/;
        autoindex off;
        sendfile on; 
        tcp_nopush on; 
        tcp_nodelay on; 
        keepalive_timeout 100;
    }   

    location /ecwid_fu_scripts/ {
        index index.php;
        root /home/ankush/;

        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }   

    location / { 
        proxy_pass http://localhost:9001;
    }   

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}
Run Code Online (Sandbox Code Playgroud)