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.
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
- How to enable breadcrumb in Eclipse/STS
- How to import Maven project in Eclipse
- svn: There are unfinished transactions detected
- How to redirect from HTTP to HTTPS on Tomcat Server
- IntelliJ IDEA – Find file containing text shortcut
- wamp- Could not execute menu item (internal error): The service has not been started
- Shortcut key to evaluate expression/variable in IntelliJ IDEA
- How to create new role and grant permission to role in JasperReports Server
- How to install Maven on Windows
- How to install Apache 2.4 and PHP 8 on a Windows Machine