I wanted to redirect/rewrite my name.php files to /name/ I found the solution on another topic (http://stackoverflow.com/questions/5527789/htaccess-rewrite-within-directory-hide-php-extension-and-force-trailing-slash)
Though, I wanted to learn it myself and started from scratch. I first used this one, which makes eg .com/test/ show the content of .com/test.php:
RewriteEngine On
RewriteRule ^(.*)/$ $1.php
Then I tried the following, by itself, which redirects .com/test.php to .com/test/:
RewriteEngine On
RewriteRule ^(.*)\.php$ http://www.mydomain.info/$1/ [R=301]
So, both work on their own. But when I combine them, I get an loop error, even when I add [L] to it, which should mean the rules should only be used once. So this doesn't work:
RewriteEngine On
RewriteRule ^(.*)/$ $1.php [L]
RewriteRule ^(.*)\.php$ http://www.mydomain.info/$1/ [L,R=301]
I've probably made some stupid error but it seems logically to me... Hope someone can point out my error. Thanks.
Because you have an external redirect with the R=301
, adding L
to it doesn't help as much as you need, as the redirect will come back to the server as a brand new request - where it again matches your first rewrite rule.
Instead, you need something like this:
RewriteCond %{THE_REQUEST} ^\w+\ /(.*)\.php\ HTTP/
RewriteRule ^ /%1/ [R=301]
RewriteRule ^(.*)/$ $1.php
Note that THE_REQUEST
matches the entire line of the original request, eg GET /index.php HTTP/1.1
. Even when %{REQUEST_URI}
is rewritten to .php
as part of the 2nd rule (where it will match on an internal sub-request), %{THE_REQUEST}
is never rewritten, and this will ensure that the URL rewritten to .php
doesn't match on the sub-request and result in another redirect sent back to the client.
Remove L-flag from first rule. That would stop "executing" and the second rule wouldn't be used. At the second rule you should keep the L flag, because it is the last one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.