Kirito
Kirito

Reputation: 175

Error htaccess to hide php extension, just hide html

I have a problem to hide php extension on my website using htaccess. I saw a lot of webs to try to fix it and nothing. But just html extension is hidden for me.

On my htaccess I have this to hide extensions (it's right after errors pages what is the first on my htaccess, but I don't think that influences):

#hide extensions 
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html

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

I can access to html files without extension, but for php files, I can't (404).

I deleted htaccess file and created it again but nothing. And of course, on links to php and html files, I don't put the extension (for example url/file instead of url/file.php).

Upvotes: 2

Views: 633

Answers (1)

MrWhite
MrWhite

Reputation: 45829

Assuming your .htaccess file is in the document root of your site then try the following instead:

Options -MultiViews

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule (.+) $1.html [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.+) $1.php [L]

The $1 backreference in the RewriteCond TestString (ie. %{DOCUMENT_ROOT}/$1.php) is a backreference to the captured group in the RewriteRule pattern (ie. (.+)), ie. the requested URL-path. This is the same backreference as used in the RewriteRule substitution (ie. $1.php).

A bit more explanation...

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

The condition here that checks the existence of the requested resource plus the file extension is not strictly correct, depending on your file structure. It's not necessarily checking the same file that you will ultimately rewrite to in the following RewriteRule. See my answer to this ServerFault question for a detailed explanation of this.

The L flag is missing on the RewriteRule, so processing will continue through the file and could be getting rewritten again.

MultiViews needs to be disabled (if not already) for the rewrite to be successfully processed. This probably does not affect you currently, but if your rewrite included URL parameters; they would be missing. (The effect of MultiViews is that mod_negotation would issue an internal subrequest for file.php before your mod_rewrite directive is processed.)

Upvotes: 2

Related Questions