In this tutorial, I am going to show you how you can remove the .php extension from the filename using .htaccess.
Many times web dev wants to remove .html or .php extensions to make URLs more SEO friendly.
It is very easy to remove the file extension.
This tutorial will help to get id done by using .htaccess file.
Removing .php Extension from URL
To remove the .php extension from a PHP file, you have to add the given below script in .htaccess file.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]
Now you can link pages inside HTML without extension.
<a href="http://domain.com/forum">Forum</a>
Now when the user will access /forum it will show the contentĀ of forum.php file. But if someone will access using /forum.php, then it will not redirect to /forum.
So to make redirection you have to add some more code in your .htaccess file.
So the Complete .htacess code will be
RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]
Removing .html Extension from URL
If you want to remove .html extension, then simply add the given below snippet in your .htaccess file
RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [NC,L]
So now you can link .html page without extension on your web page. But when user will try to access with .html it will not redirect to without extension page.
So to make redirection you have to add some more code in your .htaccess file.
So the Complete .htacess code will be
RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [NC,L]
Conclusion
You have learned how to remove .php, .html file extension from URL using .htaccess file.