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

我有我的Nginx设置的三个要求:

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

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

 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; } } 

你的问题是root指令,以及这个root的范围。

 location /ecwid_fu_scripts/ { root /home/ankush/ecwid_fu_scripts/; 

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

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

  1. 将该位置块的root更改为/ home / ankush /。
  2. 或者重构你的项目结构,所有的东西都放在一个相关的项目文件夹中 现在,将全局root (任何位置块之外的指令)设置为新的项目文件夹名称(假设在server_name指令之后是root /home/ankush/ecwid_files/; )。

现在,我们仍然需要在location /ecwid_fu_scripts/ block中添加location ~ \.php$ block的内容,因为当root改变时,与这个新根相关的东西需要在同一个块中使用。 这是因为这种types的陷阱 :ecwid_fu_scripts的位置块是说它是一个.php文件,它try_files,然后它完成这个块,并发送到下一个相关的块:全球性的location ~ \.php$ 。 问题是,它不知道什么是root ,因为它不是全局定义的。 因此,该块中的fastcgi_pass没有得到完整的path。

所以最后,你的configuration将如下所示:#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; } }