Language browser detection and action rewrite

Viewed 51

Till now I have been using htaccess to rewrite ?action only with this code:

RewriteCond %{QUERY_STRING} ^action=([^&\s]+)$
RewriteRule ^(?:index\.php|)$ /%1? [R=301,L]


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\s\/]+)/?$ index.php?action=$1&r [L,QSA]

Now I dived into a multi language website and I would like to detect user´s browser language and based on this information redirect him to his language version

And to rewrite this:

index.php?lang=en&action=subpage

into

en/subpage
1 Answers

You can have your rules like this in site root .htaccess:

RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /(?:index\.php)?\?lang=([^\s&]+)&action=([^\s&]+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L,NE]

# add default language prefix
RewriteCond %{HTTP:Accept-Language} ^([a-z]{2})- [NC]
RewriteRule ^(?![a-z]{2}/)[^/]*/?$ /%1%{REQUEST_URI} [L,R=301,NE]

# internal forward from pretty URL to actual one
RewriteRule ^([a-z]+)/([\w-]+)/?$ index.php?lang=$1&action=$2 [L,QSA,NC]
Related