Hide or Remove php or html File Extension In Nginx

Hide or Remove php or html File Extension In Nginx

It shows how to hide or remove the php or html extension by configuring the Nginx server block.

July 05, 2020

You might have seen the extensions including .php, .html, or .htm while accessing the web pages. It's because of the webserver directly serving the file without hiding the extension. We can hide or remove the file extension from the URL by updating the server block.

Prerequisites

This tutorial assumes that the Nginx Web Server is already installed on either the local or remote system.

Update Server Block

This section shows the configuration required to hide the file extension from the URL. The extension could be either html or htm or php.

The default server block should be similar to the server block as shown below.

server {
listen 80;
server_name example.com www.example.com;

root /var/www/example.com/html;

index index.html index.htm;

location / {
try_files $uri $uri/ =404;
}
}

Now update the serer block to hide the html extension from the URL as shown below.

# Update Server Block
sudo nano /etc/nginx/sites-available/example.com

# Update
server {
listen 80;
server_name example.com www.example.com;

rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;
rewrite ^/(.*)/$ /$1 permanent;

root /var/www/example.com/html;

index index.html index.htm;

location / {
try_files $uri/index.html $uri.html $uri/ $uri =404;
}
}


# Save and Exit - Ctrl + o -> Enter -> Ctrl + x

# Reload Nginx
sudo systemctl reload nginx
# OR
sudo service nginx reload

Now try to access the HTML file without the .html extension. It should show the output of the HTML file.

Similar to the HTML, we can also hide the PHP extension by updating the server block. The below-mentioned example hides both html and php extensions from the URL.

server {
listen 80;
server_name example.com www.example.com;

rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;
rewrite ^/(.*)/$ /$1 permanent;

root /var/www/example.com/html;

index index.html index.htm index.php;

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

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

# pass the PHP scripts to FastCGI
location ~ \.php$ {
try_files $uri =404;
fastcgi_intercept_errors on;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
include fastcgi_params;
}

# deny access to .htaccess files
location ~ /\.ht {
deny all;
}
}

Summary

This tutorial provided the configurations required to hide the html extension or php extension or both extension from the URL by updating the server block of Nginx Web Server.

Write a Comment
Click the captcha image to get new code.
Discussion Forum by DISQUS