301 Redirect *.php to *.html via .htaccess?

2019-02-16 03:59发布

问题:

Currently I'm rewriting all incoming requests for *.html to *.php in my .htaccess:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

RewriteRule ^(.*).html$ $1.php [QSA]

ErrorDocument 404 /404.html

So /something.html is rewritten to /something.php.

However, /something.php is still directly accessible in the browser. Now I want it to redirect to /something.html when people are accessing it in the browser, so as to avoid 2 distinct URLs for the same page of content.

Is this possible to do in my .htaccess? How? I tried R=301 but it's always a redirect loop or something. Any help would be appreciated. Thanks!

回答1:

Add this above your RewriteRule ^(.*).html$ $1.php [QSA] rule:

RewriteCond %{THE_REQUEST} \ /(.+)\.php
RewriteRule ^ /%1.html [L,R=301]

That will redirect the browser/client to the same request but with a .html instead of a .php.