如何让Nginx将所有不存在的文件请求redirect到单个php文件?

我有以下nginx的vhostconfiguration:

server { listen 80 default_server; access_log /path/to/site/dir/logs/access.log; error_log /path/to/site/dir/logs/error.log; root /path/to/site/dir/webroot; index index.php index.html; try_files $uri /index.php; location ~ \.php$ { if (!-f $request_filename) { return 404; } fastcgi_pass localhost:9000; fastcgi_param SCRIPT_FILENAME /path/to/site/dir/webroot$fastcgi_script_name; include /path/to/nginx/conf/fastcgi_params; } } 

我想redirect所有不匹配存在的文件的请求到index.php。 目前对于大多数URI来说,这个工作正常,例如:

 example.com/asd example.com/asd/123/1.txt 

asdasd/123/1.txt都不存在,所以他们被redirect到index.php,并且工作正常。 然而,如果我把example.com/asd.php放在url中,它会尝试寻找asd.php ,当它找不到它时,它会返回404而不是将请求发送到index.php

有没有办法让asd.php也发送到index.php如果asd.php不存在?

通过你的额外评论这听起来像它可能是最优化的方式,但它不是一个漂亮的configuration。

 server { listen 80 default_server; access_log /path/to/site/dir/logs/access.log; error_log /path/to/site/dir/logs/error.log; root /path/to/site/dir/webroot; index index.php index.html; location / { try_files $uri $uri/ /index.php; } location ~ \.php$ { try_files $uri @missing; fastcgi_pass localhost:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /path/to/nginx/conf/fastcgi_params; } location @missing { rewrite ^ /error/404 break; fastcgi_pass localhost:9000; fastcgi_param SCRIPT_FILENAME $document_root/index.php; include /path/to/nginx/conf/fastcgi_params; } } 

你想要做的是自定义错误页面相同。 你可以使用nginx的error_page属性来实现这一点。 按照链接了解更多信息

http://wiki.nginx.org/HttpCoreModule#error_page

哇,我想所有你想replace的代码是:

 error_page 404 /index.php 

…如果我读了你想要的东西。

我认为问题在于,您正在使用“try_files”以及您的位置中的“if”语句。 从文档中,try_files应该是if和mod_rewrite样式存在检查的替代。 从nginx维基,“try_files”页面( http://wiki.nginx.org/HttpCoreModule#try_files ):

“try_files基本上代替了典型的mod_rewrite风格的文件/目录存在检查,它应该比if更有效率 – 请参阅IfIsEvil”

检查“if”wiki页面( http://wiki.nginx.org/NginxHttpRewriteModule#if ):

“注意:在使用之前,请看看if是不是邪恶的页面,并考虑使用try_files代替。

所以,如果检查并只停留在“try_files”,请尝试删除。 这应该检查是否存在任何页面(包括asd.php或任何其他endind在.php),并返回到index.php如果没有find它。

这是与我合作!

  location /anyfolder { error_page 404 /yourhandler.php?fnf=$uri; } 

理查德,根据陷阱指南build议在php.ini中设置“cgi.fix_pathinfo = 0”,因为它解决了nginx和php之间的潜在漏洞 。

我想redirect所有缺less的PHP文件到自定义内部/error404错误页面。 我将发布在排列期间find我的解决scheme。

 error_page 404 /error404; 

没有帮助我。 location组合, @missingrewritebreak都没有。 但

 location ~ \.php$ { # this is it! $fastcgi_script_name points to my url try_files $fastcgi_script_name = /error404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_param SCRIPT_FILENAME /var/www$fastcgi_script_name; ... etc.