How to Remove File Extension .php, .html from URL using .htaccess

Here now we going to see how to remove the file extension .php, .html from the URL using .htaccess. The extension is a very important part for any files because extensions can only identify what kind of file you have. Every file format has it’s won extension example .html, .php, .css, etc., If you try to remove the file extension from the address bar and now you try to execute the URL it automatically redirect to .html or .php extension in the address bar. Using .htaccess you can remove this file extension from the address bar the rewrite method will help to solve this issue. The main purpose of removing the file extension is to secure your website from the hackers and for SEO (Search Engine Optimization). So here is the complete step by step tutorial for removing file extension.
First, create a .htaccess file in your root folder and add the following code in your .htaccess file to remove file extension. If you can’t see the .htaccess file here you here an article.
Removing .php Extension from URL
The following code will help to remove .php extension, for example from http://yourdomain.com/contact.php to http://yourdomain.com/contact. Like this, the URL comes in the address bar.
1 2 3 |
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^.]+)$ $1.php [NC,L] |
In case of user try to access the contact.php this will not redirect. So in this now you need to write a few more rules in the .htaccess file. Below you have the code copy and past it in your .htaccess file.
1 2 3 4 5 6 |
RewriteEngine on RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC] RewriteRule ^ /%1 [NC,L,R] RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^ %{REQUEST_URI}.php [NC,L] |
Removing .html Extension from URL
As same like .php extension here you can remove the .html extension, for example, you need to remove the .html extension from http://yourdomain.com/about.html to http://yourdomain.com/about.
1 2 3 |
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^.]+)$ $1.html [NC,L] |
By adding the above code the user can access the http://yourdomain.com/about URL in the browser. Now you need to redirect complete URL. Now by adding the below code, you will redirect the users which typed complete URL from http://yourdomain.com/about.html to http://yourdomain.com/about.
1 2 3 4 5 6 |
RewriteEngine on RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC] RewriteRule ^ /%1 [NC,L,R] RewriteCond %{REQUEST_FILENAME}.html -f RewriteRule ^ %{REQUEST_URI}.html [NC,L] |
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]