What is wrong with this simple rewrite rule that doesnt redirect?

此生再无相见时 提交于 2019-12-11 10:59:05

问题


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.



来源:https://stackoverflow.com/questions/52688593/what-is-wrong-with-this-simple-rewrite-rule-that-doesnt-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!