You may have seen some .php and .asp extension in url link. These extensions sometimes disclose the backend technology of website. You may want to hide these file extensions for SEO friendly url or you may want to change backend technology in fuure, and at that time it doen't affect your urls if you have already removed file extension.
In this article, I will show you how you can remove specific file extension from url using apache.
Your project must contains .htaccess file at the root of project directory with apache option. In this file, there is mod_rewrite directive. If there is no any file in the root directory, you need to create it.
Remove .html extension from url
RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]
In the above code, first we need to on RewriteEngine. Then we have added new url with html removed. We have also redirect .html url to non .html urls. This will prevent search engines to generate duplicate links of the same url.
Now if your site link is https://laravelcode.com/demo.html
and when you try to access it, it will be 301 redirect to https://laravelcode.com/demo
url.
Removing .php extension from URL
.php extension is used for php web application. Same way you can remove .php extension from the url. Any url with .php will redirect to non .php url. For example, if you visit website https://laravelcode.com/articles.php
it will redirect to https://laravelcode.com/articles
RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]
Add trailing slash(/) .htaccess
Sometimes you may want to add trailing slash at the end of link. Here is how you can add it. So if you go to https://laravelcode.com/articles
it will be redirect to https://laravelcode.com/articles/
RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]
I hope you liked the article and help in your web development.