How to remove .php and .html from URLs using .htaccess

Posted in Web design and development  on Dec 12, 2018

You most probably have visited many websites and noticed that their URLs do not end with file extensions such as .html, .htm or .php.

Such URLs look like www.example.com/about instead of something like www.example.com/about.html.

Websites made using most of the Content Management Systems(CMS) eg Wordpress or PHP frameworks such as Laravel also do not show file extensions and it has become like a standard for URLs of late.

Some of the reasons why people do it are:

  • To hide back-end programming language of the website from end users. For experts, it’s not hard to still identify the language used.
  • To make the URLs look pretty and appealing.
  • It is easy to change backend technology without affecting the URL. Eg, a page can change its file name from .html to .php without affecting the url.

In this article, I will explain how you can easily remove/hide the page name file extension using .htaccess.
.htaccess (in full Hypertext Access) file is a directory-level configuration file supported by Apache-based web servers, used for doing various web configuration(such as access control, URL redirections etc) to the directory in which is placed and all sub-directories in it.
To remove the .php extension, add the code below to your .htaccess file:

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

Incase there is “RewriteEngine On” line some where on top of your code, don’t repeat it. Just copy and paste the last two lines.
The above code as it is, will allow you to access a URL /about and show you content from about.php. However, still the users will be able to access the /about.php URL without getting redirected to /about.
To force the redirection whenever a user types the URL in full, you will need to add some more code to the .htaccess file as shown bellow:

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

This will force the visitors to get redirected to /about whenever they type /about.php.

To remove .html file extensions, the above code will work by just substituting .php with .html in the code as shown below:

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