没有初始path组件的nginx位置

我有一个位置块,看起来像这样:

root /var/www/ProjectP; location /p/ { index index.php; try_files $uri $uri/ =404; } location ~ /p/.*\.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.0-fpm.sock; } 

为了做这个工作,我创build了一个目录/var/www/ProjectP/p/ ,这是一个非常糟糕的黑客攻击,因为它将知道项目在项目中的位置,而不是nginx。 Nginxconfiguration应该能够将其移动到/pp/而不需要修改项目P.

这个特定的项目没有proxy_pass指令,但接下来会发生,然后我的黑客是不太可能工作。

我相信nginx有一个正确的方法来处理这种常见的东西,但我还没有find它。 任何指针?

更新1

正如@RichardSmith指出的那样,正确的做法肯定是一个别名指令。 在静态内容上testing这个效果很好:

 location /a/ { alias /var/www/ProjectA/; index index.html; try_files $uri $uri/ =404; } 

当我用php代码做同样的事情时,我获得了一半的成功:

 location /p/ { alias /var/www/ProjectP/; index index.php; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 location ~ /p/(.+\.php)$ { alias /var/www/ProjectP/$1; include snippets/fastcgi-php.conf; # With php7.0-fpm: fastcgi_pass unix:/run/php/php7.0-fpm.sock; ## These next are largely set via snippets/fastcgi-php.conf. ## Trying them here doesn't help, but I leave them (commented out) ## for the moment... #fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #include fastcgi_params; #fastcgi_param SCRIPT_FILENAME $uri; } 

testing一个非PHP文件,我确认第一个块的作品。 但第二块不,所以php文件不能正常服务。 (我得到了404的。)我已经在最后的注释fastcgi指令上尝试了几个变种,但显然不是正确的组合。

更新2

这工作。

 root /var/www/; location /p/ { alias /var/www/ProjectP/; index index.php; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; # Pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 location ~ \.php$ { include snippets/fastcgi-php.conf; # With php7.0-fpm: fastcgi_pass unix:/run/php/php7.0-fpm.sock; fastcgi_param SCRIPT_FILENAME $request_filename; } } 

您的location区块至less有一个问题。

如果您请求http://www.example.com/p/test.php $1variables的内容将是test.php

这意味着你的

 alias /var/www/ProjectP/$1; 

将文档根目录设置为/var/www/ProjectP/test.php

那么,

 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 

定义发送到PHP进程的实际文件path来定位文件。 $document_root包含这个转换中的aliaspath, $fastcgi_script_name包含请求中的文件名。

所以,最后的结果就是,对http://www.example.com/p/test.php的请求最终会导致PHP进程的文件名/var/www/ProjectP/test.phptest.php 。 所以会有一个404返回。

解决方法是只使用:

 alias /var/www/ProjectP 

在PHP location块。

这工作。

 root /var/www/; location /p/ { alias /var/www/ProjectP/; index index.php; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; # Pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 location ~ \.php$ { include snippets/fastcgi-php.conf; # With php7.0-fpm: fastcgi_pass unix:/run/php/php7.0-fpm.sock; fastcgi_param SCRIPT_FILENAME $request_filename; } }