Remove multiple file extensions using RewriteRule in htaccess.

How to remove multiple file extensions using RewriteRule in htaccess ?



.htaccess is a directory level configuration file used on apache server. Many users who don't have access to their main server.config file use htaccess to rewrite URLs and configure other custom server settings. Htaccess is often used by Apache users to shorten URLs when they want to turn a long and non-memorable URL into short and memorable one. One of the most used rewriteRule on htaccess is "File extension removal" rule. Users find it easier then server.config to RewriteRule through htaccess. In this post I will show you how you can remove any file extension using htaccess.



What you will need:



  • Apache server

  • Mod-rewrite

  • .htaccess support


Apache server


You must have an apache server to use RewriteRules.


Mod-rewrite


Mod-rewrite is a rewrite module provided by apache. You must have this module enabled on your server in order to use RewriteRules directive. Some hosting service providers have enabled it by default but in case its not enabled ,you can enable it by adding one mazic line AllowOverride All in your server.config file. If you don't have access to this file then ask your hosting service to enable it for you.


.htaccess


.htaccess is where you will write rule code. htaccess is a dot perfix file. If your hosting service hasn't enabled it then ask them to enable it.



Remove file extension using RewriteRule


With a RewriteRule directive, you can remove the traling .php from your php files. For example You will only type /filename instead of /filename.php . Filenames with extension do not cause any SEO issues but if you remove the extension then appearance of URL becomes awasome. The following is the rule to remove .php extension from urls. You can edit it to remove other extensions accordingly by just replacing .php with your file extension :


RewriteEngine on
#2)
RewriteRule %{THE_REQUEST} /(.*)\.php [NC]
#2)
RewriteRule (.*) /%1 [L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*)/?$ /$1.php [L]



The rewrite rule above would redirect any php file url ie (foo.php) to remove the extension. The first set of rule redirects /file.php to /file and the second one then internally maps /file to its original location /file.php .



Remove multiple file extensions using RewriteRule in htaccess


It is possible to remove multiple file extensions using two rules. You can capture file extensions using regex in RewriteCond and then rewrite the request accordingly.


RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.(php|html|css) [NC]
RewriteRule ^ /%1 [L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*)/?$ /$1.php [NC,L]

The simple approach works for any file extension you want to remove.

Post a Comment

0 Comments