Search code examples
phpwordpressnginxpermalinks

Enabling both permalinks and extensionless php routing not working in Nginx


I have my nginx.conf file as follows:

server {
    ...    
root /var/www/html;

            # Add index.php to the list if you are using PHP
            index index.php index.html index.htm index.nginx-debian.html;

            server_name mydomain.com;

            if (!-e $request_filename)
            {
             rewrite ^.*$ /index.php last;
            }


            location / {

                    try_files $uri $uri/ @extensionless-php;
            }


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

            location @extensionless-php {
                    rewrite ^(.*)$ $1.php last;
            }
}

I have WordPress installed on Nginx in Ubuntu server running.

I have a navigation menu named Resume that leads to example.com/resume and shows a pdf file that is actually myname_resume.pdf but I have putted resume.php in the root directory and this php script gets the contents of myname_resume.pdf and displays it as pdf file.

I want my url never append any file extension .pdf or .php no matter if you anyone can expicitily write url.php and it would give the same result and hence I had done this. This configuration of extensionless-php was working fine when I putted this code:

if (!-e $request_filename)
{
    rewrite ^.*$ /index.php last;
}

As I have WordPress installed, I wanted to give permalink to a page created on WordPress as example.com/contact and for enabling permalink, I had to add above small configuration. Now the permalink is opening but the mydomain.com/resume is giving 404 error. How to enable both of them or is there any good method to achieve the same?


Solution

  • Rather than appending the .php to any non-existent files - you could change the logic so that the .php is appended to the URI only if a PHP file actually exists.

    For example:

    location / {
        try_files $uri $uri/ @rewrite;
    }
    location @rewrite {
        if (-f $request_filename.php) {
            rewrite ^ $uri.php last;
        }
        rewrite ^ /index.php last;
    }
    location ~ \.php$ {
        try_files $uri =404;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }
    

    See this caution on the use of if.