remove .php from url in nginx

How to Remove .php from URL in NGINX

By default, NGINX shows .php and .html in URLs on a website. This can look very annoying for visitors who have to enter .php and .html extensions in their URLs. Also, it can lead to security issues with attackers exploiting PHP & HTML vulnerabilities. In this article, we will look at how to remove .php from URL in NGINX.

How to Remove .php from URL in NGINX

Here are the steps to remove .php from URL in NGINX.

1. Open NGINX configuration file

Open terminal and run the following command to open NGINX configuration file.

$ sudo vi /etc/nginx/nginx.conf

Also read : How to Convert List to String in Python

2. Remove .php from URL

Add the following lines in the NGINX configuration file, inside server block

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;

Basically, in the above code, try_files will check to see if requested URL can be served using its static file. If it is not available, it will be sent to the fallback @extensionless-php to serve the dynamic files.

Also read : How to Run Scripts on Startup in Ubuntu

3. Restart NGINX Server

Restart NGINX server to apply changes.

$ systemctl reload nginx

That’s it. Now open the browser and enter your website URLs without .php and .html extensions, and they should work properly.

Also read : How to Install HAProxy in Ubuntu

Leave a Reply

Your email address will not be published. Required fields are marked *