Dail
Dail

Reputation: 81

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!

Upvotes: 8

Views: 24369

Answers (4)

Sam Bauers
Sam Bauers

Reputation: 413

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.

Upvotes: 6

rebe100x
rebe100x

Reputation: 1493

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.

Upvotes: 1

zigo928
zigo928

Reputation: 21

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

Upvotes: 2

Ikke
Ikke

Reputation: 101231

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.

Upvotes: 15

Related Questions