Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 919
Dail Avatar asked May 07 '11 08:05

Dail


3 Answers

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.

like image 93
Ikke Avatar answered Oct 02 '22 05:10

Ikke


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.

like image 38
Sam Bauers Avatar answered Oct 02 '22 06:10

Sam Bauers


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

like image 37
zigo928 Avatar answered Oct 02 '22 05:10

zigo928