我不擅长编写modrewrite访问规则,并希望实现以下场景:
virtual url /en/shop.php redirects to /shop.php?lang=en
已经有了,但实际问题在modrewrite环境中:
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
我已经尝试了几条规则,但最后一条导致无限循环,我无法弄清楚出了什么问题..:/请帮忙
这是我的.htaccess文件:
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]
答案 0 :(得分:2)
这是导致重定向循环的行:
RewriteRule ^(en|de)/(.*)$ $2?lang=$1&%{query_STRING} [R=301,L]
因为它将浏览器重定向到/?lang=en
(例如)。然后是第一条规则:
RewriteRule ^$ en/ [R=301,L]
将其重定向到/en/?lang=en
,然后最后一条规则将其重定向到/?lang=en
,然后是第一条规则,等等。
你可能意味着最后一条规则是内部规则,另外,你的第一条规则需要检查是否已有查询字符串参数," 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 --------------------------------------^