我正在尝试重写/重定向传入的请求,以便它们始终以语言代码为前缀,但希望保留最初请求的路径:
example.org/de/ -> rewrite to example.org?lang=de
example.org -> redirect to example.org/de/ which will then be rewritten
to example.org?lang=de
example.org/en/ -> rewrite to example.org?lang=en
example.org/foo/bar -> redirect to example.org/de/foo/bar wich will
then be rewritten to example.org/foo/bar?lang=de
这些是我对此的想法:
RewriteBase /
# No 'lang' key in query string
RewriteCond %{QUERY_STRING} !lang=(en|de)
# AND request_uri does not start with 'en' or 'de'
RewriteCond %{REQUEST_URI} !^(en|de)
# Redirect to lang prefixed uri while keeping the initial uri
RewriteRule ^(.*)$ de/%{REQUEST_URI} [L,R=301,QSA]
# Add language prefix as query parameter
RewriteRule ^(en|de) ?lang=$1 [L,QSA]
此外,我想保留传入请求的任何查询字符串,并将其附加到重定向/重写的uri。 实际上我的想法对我来说听起来很合理,但我得到了无休止的重定向。如果你能指出我正确的方向,我会很高兴,因为我已经失去了几个小时和几个小时
更新
最后在anubhava的帮助下,我可以设法解决整个问题,并希望分享最终的解决方案
# 1) Prefix ALL request uris with /<lang>/. Depending on the `Accept-Language`
# header 'de' or the default 'en' is used as prefix.
# 2) Rewrite real files by stripping off the /<lang>/ prefix but still add
# the ?lang=<lang> query parameter
# 3) Add a trailing slash and append ?lang=<lang> query parameter
RewriteEngine On
RewriteBase /
# No 'lang' key in query string and 'de' as accepted language header.
# Redirect to 'de' prefixed uri
RewriteCond %{QUERY_STRING} !lang=(en|de) [NC]
RewriteCond %{HTTP:Accept-Language} (de) [NC]
RewriteRule !^(en|de)(/.*)?$ de%{REQUEST_URI} [L,NC,R]
# Redirect anybody without 'de' as accepted language to the 'en' version
RewriteCond %{QUERY_STRING} !lang=(en|de) [NC]
RewriteRule !^(en|de)(/.*)?$ en%{REQUEST_URI} [L,NC,R]
# Strip lang prefix in case this a real file
RewriteCond %{REQUEST_URI} ^/(en|de)(/.*)$ [NC]
RewriteCond %{DOCUMENT_ROOT}%2 -f
RewriteRule ^(en|de)(/.*)$ $2?lang=$1 [L,NC]
# Add trailing slash to those request which make it till here
RewriteRule ^(en|de)(/.*)?/?$ $2/?lang=$1 [L,NC,QSA]
非常感谢你的帮助!
答案 0 :(得分:2)
您可以遵守以下规则:
RewriteEngine On
# No 'lang' key in query string
RewriteCond %{QUERY_STRING} !lang=(en|de) [NC]
# Redirect to lang prefixed uri while keeping the initial uri
RewriteRule !^(en|de)/ /de/%{REQUEST_URI} [L,NC,R=301]
RewriteRule ^(en|de)(/.*)?$ $2?lang=$1 [L,NC,QSA]
清除浏览器缓存后进行测试。