5

I have this nginx vhost config:

server {
        listen 8081;
        server_name blocked_server;
        root /home/gian/blocked_server;
        access_log off;
        error_log off;
        index index.php index.html index.htm index.nginx-debian.html;

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        }

        location ~ / {
                try_files $uri $uri /index.php;
        }
}

it redirects all urls to index.php except when the url ends with .php extension.

for example this works: http://localhost/somethingthatdontexist

but this returns a 404 and don't redirect to index.php http://localhost/somethingthatdontexist.php

how can i redirect url with .php extension that don't exist to index.php?

3
  • 1
    Try adding try_files $uri /index.php; to your location ~ \.php$ block. Commented Jun 24, 2018 at 8:53
  • i tried adding it to the location ~\.php$ block and I can't reload nginx due to this error: nginx: [emerg] "try_files" directive is duplicate in /etc/nginx/snippets/fastcgi-php.conf:5 Commented Jun 24, 2018 at 8:56
  • Check the contents of the snippets/fastcgi-php.conf file. You can either change the try_files statement in there, or paste the contents of the file into the location block so you can edit it there. Commented Jun 24, 2018 at 9:01

2 Answers 2

2

I already solved the problem. First you should comment out this line or remove this line from the snippets/fastcgi-php.conf file

try_files $fastcgi_script_name =404;

then on your virtualhost config put try_files $uri $uri /index.php; before the include snippets/fastcgi-php.conf; on the location ~\.php$ block.

the location ~\.php$ block should look like this:

location ~ \.php$ {
    try_files $uri $uri /index.php;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

that should do the trick.

Sign up to request clarification or add additional context in comments.

1 Comment

or you can just set the error 404 page to be index.php as well.
0

I think the comments made on the original question by @Richard Smith (https://stackoverflow.com/users/4862445/richard-smith) are very important and should be added as an answer.

Adding try_files to the .php location is the answer but it results in an error because that option is already set in the included snippet.

Simply editing /etc/nginx/snippets/fastcgi-php.conf and changing the try_files option to your desired outcome resolves the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.