Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

.htaccess - Endless Redirect Loop by htaccess rules multi language

i'm not good in writing modrewrite access rules and would like to achieve the following scenario:

virtual url /en/shop.php redirects to /shop.php?lang=en

already got that but the actual problems are within the modrewrite environment:

if url is '/' (empty)     --> redirect to /en/  (/index.php?lang=en)
if url is '/en' or '/de'  --> redirect to /en/ or /de/ (add slash)
if an uri is "defined" like /en/shop.php -> redirect to /shop.php?lang=en

i've tried several rules but the last one results in a endless loop and i can't figure out what's wrong .. :/ please help

here's my .htaccess file:

RewriteEngine On
RewriteBase /   

# empty url -> redirect to en/
RewriteRule ^$ en/ [R=301,L]

# url is ONLY '/en' or '/de' -> redirect to /en/ or /de/ (adding slash)
RewriteRule ^(en|de)$  $1/ [R=301,L]

# now all urls have en/ de/ -> parse them
RewriteRule ^(en|de)/(.*)$  $2?lang=$1&%{query_STRING} [R=301,L]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the line that is causing the redirect loop:

RewriteRule ^(en|de)/(.*)$  $2?lang=$1&%{query_STRING} [R=301,L]

Because it is redirecting the browser to /?lang=en (for example). Then the first rule:

RewriteRule ^$ en/ [R=301,L]

Redirects it to /en/?lang=en, then the last rule redirects it to /?lang=en, then the first rule, etc.

You probably meant the last rule to be internal, additionally, your first rule needs to check if there's already a query string parameter, "lang":

RewriteEngine On
RewriteBase /   

# empty url -> redirect to en/
RewriteCond %{QUERY_STRING} !lang=(en|de)
RewriteRule ^$ en/ [R=301,L]

# url is ONLY '/en' or '/de' -> redirect to /en/ or /de/ (adding slash)
RewriteRule ^(en|de)$  $1/ [R=301,L]

# now all urls have en/ de/ -> parse them
RewriteRule ^(en|de)/(.*)$  $2?lang=$1&%{query_STRING} [L]
# no "R=301" here --------------------------------------^

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...