What is wrong with this simple rewrite rule that d

2019-08-11 02:02发布

问题:

Good day to everyone,

I'm struggling trying to understand what is wrong with this simple rule that doesn't work. I have a website that has URLs like that: site.com/support, I now want to redirect all the URLs site.com to site.com/en, site.com/support/ to site.com/en/support/, ....

After many tries and search, I came up with the 2 following rules:

RewriteRule ^(?![a-z]{2}/)(.*)$ /en/$1 [R=301,L] # redirect to default language
RewriteRule ^([a-z]{2})/(.*)$ /$2?lang=$1 [QSA,L]

each of these rules work perfectly separately, but result in a too many redirects when combined (?lang=en&lang=en&lang=en...)

any one could tell me pls what is wrong?

Thanks

回答1:

Problem is that both rules are modifying REQUEST_URI and causing each other to execute repeatedly until browser detects a redirect loop and stops redirecting with an error.

You can fix it by using:

RewriteEngine On

# redirect to default language
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteRule ^(?![a-z]{2}/)(.*)$ /en/$1 [R=301,L,NE]

RewriteRule ^([a-z]{2})/(.*)$ /$2?lang=$1 [QSA,L]

RewriteCond %{ENV:REDIRECT_STATUS} !200 condition will prevent redirect loop as Apache will set REDIRECT_STATUS env variable to 200 after first successful execution of 1st rule.