olo
olo

Reputation: 5271

htaccess remove html and php duplicated is not working

this snippet works fine for removing php extension

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

However, if I add html condition, it will not work

RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

Did I do something wrong?

Upvotes: 0

Views: 96

Answers (1)

Felipe Alameda A
Felipe Alameda A

Reputation: 11809

You may try this instead, in one .htaccess file at root directory:

Options +FollowSymlinks -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME}      !-d
RewriteCond %{REQUEST_FILENAME}.php   -f
RewriteCond %{REQUEST_URI}   !\.php   [NC]
RewriteRule .*   %{REQUEST_URI}.php   [NC,L]

RewriteCond %{REQUEST_FILENAME}      !-d
RewriteCond %{REQUEST_FILENAME}.html  -f
RewriteCond %{REQUEST_URI}   !\.html  [NC]
RewriteRule .*   %{REQUEST_URI}.html  [NC,L]

You should be aware the implementation in your code works only when the request doesn't have a trailing slash. I just modified your code to work, but I think it's worth nothing that problem. For example:

For a request like http://example.com/filename/, the file to match with condition RewriteCond %{REQUEST_FILENAME}.php -f is filename/.php. That file can't exist, therefore, the respective rule will be never used.

Option to remove the trailing slash when present:

Add these lines after RewriteEngine On in the previous code:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI}  /(.*[^/]+)/$ [NC]
RewriteRule .*              /%1          [NC,L]

Upvotes: 1

Related Questions