How to rewrite if file not found using NGINX

拟墨画扇 提交于 2019-12-07 02:57:50

问题


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/nginx/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!


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/5920081/how-to-rewrite-if-file-not-found-using-nginx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!