NGINX目录中的PHP别名不起作用

我有一个全新的Ubuntu 14.04服务器安装。 我已经安装了nginx,php等…

server { listen 80; listen [::]:80; server_name testone.local; root /var/www/htmlone; index index.html; # pass the PHP scripts to FastCGI server listening on the php-fpm socket location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location /alias { alias /var/www/htmlalias; location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } } 

如果我在/var/www/htmlone使用一个简单的php脚本,php按预期执行。 如果我在/var/www/htmlalias使用相同的脚本,它不会按预期执行。 如果我在/var/www/htmlalias放置了一个HTML脚本,它会按照预期显示,所以这个别名可以作为一个别名,但是不会执行php文件,但是PHP在主根目录下工作。

我发现许多服务器故障的问题,这个一般的设置应该工作,但事实并非如此。 有没有人看到我可能做错了什么? 我在错误日志中看不到消息。

我应该添加这是为nginx版本:nginx / 1.8.0

你遇到的问题实际上是3年前提交的一个长期的错误,这会导致aliastry_files不能真的一起工作。

在错误页面上,Luke Howell提供了一个解决方法 ,具体如下:

 location /api { ## URL string to use for api ## alias /home/api/site_files/; ## Site root for api code ## ## Check for file existing and if there, stop ## if (-f $request_filename) { break; } ## Check for file existing and if there, stop ## if (-d $request_filename) { break; } ## If we get here then there is no file or directory matching request_filename ## rewrite (.*) /api/index.php?$query_string; ## Normal php block for processing ## location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } } 

请注意,尽pipe对于nginx来说, IF是邪恶的 ,如果可能的话应该避免 。

从我的testing上面的configuration它是存在的

 try_files $uri =404; 

在导致问题的嵌套的别名php位置内。 有了它,nginx会检查“/var/www/htmlalias/alias/index.php”(注意加上'alias'加上uri),发现它不存在,然后返回404.移除那个try_files停止它首先在磁盘上查找此文件,并将请求直接传递给fastcgi,然后从SCRIPT_FILENAME中find正确的文件。

如果你想让不存在的PHP文件给出404错误而不是PHP错误,那么以下工作:

  location /alias { alias /var/www/htmlalias; location ~ /([^/]+\.php)$ { try_files /$1 =404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } } 

首先,正则expression式捕获php文件的填充文件名(例如foo.php)为$ 1。 然后try_files检查相对于当前别名的文件是否存在,如果不存在则返回404。

然后,我们必须重写fastcgi_params中定义的默认SCRIPT_FILENAME,方法是在include之后重新定义它,因为$ request_filename由于某种原因,我不明白,完全是错误的东西(字面意思是/index.php)。

这是我解决这个问题的方法:

默认的服务器configuration(没有别名),在你的例子中:

 server { listen 80; listen [::]:80; server_name testone.local; root /var/www/htmlone; index index.html; # pass the PHP scripts to FastCGI server listening on the php-fpm socket location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } 

并从命令行创build/var/www/htmlone下的符号链接:

ln -s /var/www/htmlalias /var/www/htmlone/alias