How to Remove php, html Extension from URL using htaccess


Most of the time web developer does 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, you can use the .htaccess file. This one is the simplest way of 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 a .htaccess file?

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

Where to put the .htaccess file in the 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]

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.