.htaccess redirect + rewrite: prefix uri with language code, keeping original uri
I'm trying to rewrite / redirect incoming requests to always be the prefixed language code, but would like to keep the originally requested path:
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
These were my thoughts on this:
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]
Also, I would like to keep the query strings of the incoming request and add it to the redirected / rewritten uri. Actually my thoughts sound logical to me, but I get infinite redirection. I would be too happy if you could point me in the right direction as I am lost with watches and clocks.
Update
Finally with the help of anubhava I was able to solve this whole problem and would like to share the final solution
# 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]
Many thanks for your help!
+3
source to share
1 answer
You may have the following rules:
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]
Check it after clearing your browser cache.
+2
source to share