Digital Marriage Invitation Card

How to Remove php, html Extension from URL using htaccess


Most of the time web developer do not want to show the file extension in URL. Now the problem is how to hide or remove these extensions from the URL without coding the lengthy program or using the complex way.

To remove the extension from URL, use the .htaccess file. This one is the simplest way for removing the extensions from the URL.

Please note .htaccess is not a file extension. It's simply the .htaccess or [dot]htaccess.

How to create htaccess file

To create .htaccess file. Go to your project root directory create a new file and rename it as .htaccess.

Where to put htaccess file in project

.htaccess must be in your project root directory. To clear doubt see the image.

How to Remove php, html Extension from URL using htaccess

Hide PHP Extension

To hide the php extension from the URL, paste the below code in your .htaccess file.

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

Hide HTML Extension

To hide the html extension from the URl, paste the below code in your .htaccess file.

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

When you have added the RewriteRule in your .htaccess file. Then remove the .php or .html extension from your page.

See the example

Without adding .htaccess
<html>
<body>
	<a href="contact-us.php">Contact Us</a>
</body>
</html>
After adding .htaccess
<html>
<body>
	<a href="contact-us">Contact Us</a>
</body>
</html>

Check the full script here.

RewriteEngine On
# remove the index file
RewriteCond %{THE_REQUEST} ^.*/index
RewriteRule ^(.*)index$ http://www.example.org/$1 [R=301,L]  

# remove the .php extension 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(([^/]+/)*[^.]+)$ $1.php [L]

# redirect from .php to less php
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php http://www.example.org/$1 [R=301,L]

Share this article on: