How to remove .php, .html extensions with .htaccess

Removing .PHP Extensions

To remove the .php extension from a PHP file for example yoursite.com/wallpaper.php to yoursite.com/wallpaper you have to add the following code inside the .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Removing .Html Extensions

To remove the .html extension from a html file for example yoursite.com/wallpaper.html to yoursite.com/wallpaper you simply have to change the last line from the code above, to match the filename:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html[NC,L]

You can now link pages inside the HTML document without needing to add the extension of the page

Example :

<a href="http://domain.com/filename" title="page title">Click here</a>

Adding a trailing slash at the end

I received many requests asking how to add a trailing slash at the end, for example: yoursite.com/page/

Ignore the first snippet and insert the code below. The first four lines deal with the removal of the extension and the following, with the addition of the trailing slash and redirecting.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

GoDaddy users

In order to remove the extensions you need to enable MultiViews before. The code should look like this

Options +MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

If you’re worried that search engines might index these pages as duplicate content, add a <canonical> meta tag in the <head> of your HTML file:

<link rel="canonical" href="https://alexcican.com/post/single-post" />

Leave a Reply

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