How to rewrite if file not found using NGINX
I'm using NGINX On Ubuntu server. I have this vhost:
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/ngin开发者_如何学Cx/fastcgi_params;
}
}
I have to add a rule...
If the file/dir IS NOT FOUND use index.php
How could I change my server {} directive?
Thank you!
You can use the try_files directive:
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.
See also the front controller section on the nginx wiki.
Ikke is correct, use try_files like so:
location / {
try_files $uri $uri/ /index.php;
}
But your PHP fastcgi location is insecure. See this article to find out more about that.
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.
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
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.
精彩评论