Linux 如果使用 NGINX 找不到文件,如何重写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5920081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to rewrite if file not found using NGINX
提问by Dail
I'm using NGINX On Ubuntu server. I have this vhost:
我在 Ubuntu 服务器上使用 NGINX。我有这个虚拟主机:
server {
listen 80;
server_name *.example.com;
root /home/nginx/vhosts/example.com/web;
location / {
index index.php;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9001;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include /etc/nginx/fastcgi_params;
}
}
I have to add a rule...
我必须添加一个规则...
If the file/dir IS NOT FOUND use index.php
如果未找到文件/目录,请使用 index.php
How could I change my server {} directive?
如何更改我的服务器 {} 指令?
Thank you!
谢谢!
回答by Ikke
You can use the try_files directive:
您可以使用 try_files 指令:
try_files $uri $uri/ /index.php
This will try to find files and directories first, and if that doesn't work, it will use index.php.
这将首先尝试查找文件和目录,如果这不起作用,它将使用 index.php。
See also the front controllersection on the nginx wiki.
另请参阅nginx wiki 上的前端控制器部分。
回答by zigo928
You need to fllow setting:
您需要流程设置:
server {
listen 80;
server_name *.example.com;
root /home/nginx/vhosts/example.com/web;
location / {
index index.php;
}
location ~ \.php$ {
root /home/nginx/vhosts/example.com/web;
fastcgi_pass 127.0.0.1:9001;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include /etc/nginx/fastcgi_params;
}
}
hope help you
希望能帮到你
回答by rebe100x
I had the same problem on RH6 an EC2 and I fixed it by hard coding the $document_root
, in the param fastcgi_param
.
Hope it helped.
我在 RH6 和 EC2 上遇到了同样的问题,我通过$document_root
在 param 中硬编码, 来修复它fastcgi_param
。希望它有所帮助。
回答by Sam Bauers
Ikke is correct, use try_files like so:
Ikke 是正确的,像这样使用 try_files:
location / {
try_files $uri $uri/ /index.php;
}
But your PHP fastcgi location is insecure. See this articleto find out more about that.
但是您的 PHP fastcgi 位置不安全。请参阅这篇文章以了解更多相关信息。
For your setup you need to have something like this:
对于您的设置,您需要有这样的东西:
location ~ \.php$ {
try_files $uri /index.php;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
include /etc/nginx/fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9001;
}
Note that you should set local fastcgi_param
after including the fastcgi_params global config.
请注意,您应该fastcgi_param
在包含 fastcgi_params 全局配置后设置 local 。