Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mod_rewrite with browser language and non-www domain [closed]

I'm using the following rule to redirect the domain to EN version of the site based on browser language:

RewriteCond %{HTTP:Accept-Language} ^en.*$ [NC]
RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteCond %{QUERY_STRING} !(^q\=) [NC]
RewriteRule ^(.*)$ /en [L,R=302]

this works ok with www.domain.com but fails redirecting from now-www to www. For example, fails to redirect http://domain.com to http://www.domain.com/en, that's what i'm trying to achieve.

What should i add to the rule? Thank you!

like image 990
Jose A. Avatar asked Jan 12 '13 03:01

Jose A.


1 Answers

To redirect non-www to www, add this rule-set before the one in your question, like this:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

#This is the rule set in the question:
RewriteCond %{HTTP:Accept-Language} ^en.*$ [NC]
RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteCond %{QUERY_STRING} !(^q\=) [NC]
RewriteRule ^(.*)$ /en [L,R=302]

Since you say the actual rule-set is working fine except for the www issue, I did not modify it or test it.

What the top rule rule does, is to insert www to all URLs. That's all. It is independent from the rule in your question, but if you want to limit that conversion to EN language only, move this line:

RewriteCond %{HTTP:Accept-Language} ^en.*$ [NC]

in the last rule-set, to the first one, like this:

....
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteCond %{HTTP:Accept-Language} ^en.*$ [NC]
....

OPTION

To redirect all requests that don't match the previous language rules, just place the following lines at the bottom, after all language rules.

RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteCond %{QUERY_STRING} !(^q\=) [NC]
RewriteRule ^(.*)$ /en [L,R=302]

It will redirect by default all incoming requests to the English section.

So, your .htaccess file should look like this:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

RewriteCond %{HTTP:Accept-Language} ^sv.*$ [NC]
RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteCond %{QUERY_STRING} !(^q\=) [NC]
RewriteRule ^(.*)$ /sv [L,R=302]

RewriteCond %{HTTP:Accept-Language} ^nb.*$ [NC]
RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteCond %{QUERY_STRING} !(^q\=) [NC]
RewriteRule ^(.*)$ /nb [L,R=302]

RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteCond %{QUERY_STRING} !(^q\=) [NC]
RewriteRule ^(.*)$ /en [L,R=302]

I suggest you replace all R=302 with R=301. It's better for SEO purposes.

like image 64
Felipe Alameda A Avatar answered Oct 29 '22 17:10

Felipe Alameda A