Jesse Macleod Jesse Macleod - 1 month ago 9
Apache Configuration Question

Remove multiple file extensions with .htaccess

I have a subdomain acting as an entirely new website (subdomain.domain.com = subdomain.com). I mainly use .html files but want to get rid of those extensions (instead of http://subdomain.com/file.html, I want http://subdomain.com/file ). I've used the .htaccess code below to accomplish this.

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.html [L,QSA]


The only problem is, I also need to get rid of the .php extension of other files on the website. Most people say to duplicate the above code with .php replacing .html. I've done that; doesn't work. I've tried many other versions of the code, and still doesn't work.

Since I'm no expert at all with .htaccess, can anyone please explain how to remove both .html and .php file extensions?
Thanks in advance.

I don't believe this is a duplicate question since I haven't seen anyone else ask how to replace multiple file extensions at once.

Answer

You can use rewrite rules like this:

Options +FollowSymLinks
RewriteEngine on

# for adding .html extension if matching file exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.html -f [NC]
RewriteRule ^(.+?)/?$ /$1.html [L]

# for adding .php extension if matching file exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]