Remove .php extension with NGiNX

 
 

Removing .php or .html extension from your website URL when using NGiNX can be quite frustrating, luckily there is a quick and simple solution that we can use in order to fix this and no, it is not called .htaccess as you used to do it when using Apache as web server. It is a nice and elegant solution where you can manage this straight from your .conf file. In this short tutorial we will guide you step by step how to remove .php and .html extension from your URL when using NGiNX, this is a pretty good solution to boost your SEO and get some really nice and friendly website URLs.

Table of contents

Edit .conf file
Remove .php and .html extensions from URL
Reload NGiNX

Edit the .conf file

On our first step we’ll have to open and edit the appropriate configuration file. If you have no custom .conf file then you will typically the default file can be found at /etc/nginx/nginx.conf, please open it as shown in the example below using vi or whatever editor you like:


$ vi /etc/nginx/nginx.conf

Remove .php and .html extensions from URL

On this step we have to add the following code lines inside the server block in order to remove the .php and .html extensions from your URLs, please use the below example:


server {
...

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
    index index.html index.htm index.php;
}

location ~ \.php$ {
    try_files $uri =404;
}

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

Make sure you save the changes and lets move on to our next step.

Reload NGINX web server

Finally in order for our changes take effect we have to reload NGINX server, depending on your Linux distro you may have to use service [service_name] reload or systemctl reload [service_name], we will use systemctl on this particular example:


$ systemctl reload nginx

That’s it, now simply open a browser and go to a URL without its .php or .html extension. For example, go to /index instead of /index.php and your browser should load the page, if that doesn’t work simply restart NGiNX, that should work.

Video

No video posted for this page.

Screenshots

No screenshots posted for this page.

Source code

No code posted for this page.

About this page

Article
Remove .php extension with NGiNX
Author
Category
Published
09/04/2019
Updated
23/04/2019
Tags

Share this page

If you found this page useful please share it with your friends or colleagues.