'How to redirect all request to index.php even with .php in the url

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?



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gian Lorenzo Abaño
Solution 2 John.M