Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess rewrite based on hostname or domain name

I have two different domains (let's say www.site1.com and www.site2.com) that point to the same hosting server.

I need the two different domain names because I want to use the first one for the italian contents and the second one for the english contents. The contents are the same, unless for the language, but the domains have to be different.

So, I'd like to write a rule that lets me translate from:

  • www.site1.com to /?lang=it

  • www.site2.com to /?lang=en

I usually use the same domain name for many different languages rewriting from www.site.com/it/ to /?lang=it (of course, a transparent rewriting - the user doesn't see any different URL).

I'd like to achieve the same using different domains but I can't figure out how... I've been working on it for hours and I can't achieve what I want!

Usually I use this:

RewriteCond %{REQUEST_URI} /([a-z]{2})
RewriteRule ^([a-z]{2})[/]*$ /index.php?lang=$1 [NC,QSA]

I can't get this one work, to use different domains:

RewriteCond %{HTTP_HOST} ^www.site1\.com [NC]
RewriteCond %{REQUEST_URI} !^/index.php?lang=it
RewriteRule ^(.*)$ /index.php?lang=it [NC,QSA]

RewriteCond %{HTTP_HOST} ^www.site2\.com [NC]
RewriteCond %{REQUEST_URI} !^/index.php?lang=en
RewriteRule ^(.*)$ /index.php?lang=en [NC,QSA]
like image 897
tobia.zanarella Avatar asked Apr 19 '12 16:04

tobia.zanarella


People also ask

What is rewrite rule in htaccess?

htaccess rewrite rules can be used to direct requests for one subdirectory to a different location, such as an alternative subdirectory or even the domain root. In this example, requests to http://mydomain.com/folder1/ will be automatically redirected to http://mydomain.com/folder2/.

What does rewrite rule do?

htaccess rewrite rule includes setting a combination of rewrite condition ( RewriteCond ) tests along with a corresponding rule ( RewriteRule ) if the prior conditions pass. In most cases, these rules should be placed at any point after the RewriteEngine on line in the . htaccess file located in the website's docroot.

What is QSA in htaccess?

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle? p=1 will be rewritten as index.


1 Answers

Lawrence Cherone - Thank you, that one works like a charm! Now it works:

RewriteCond %{HTTP_HOST} ^www\.site1\.com [NC] 
RewriteRule ^(.*)$ index.php?lang=it [NC,QSA] 
RewriteCond %{HTTP_HOST} ^www\.site2\.com [NC] 
RewriteRule ^(.*)$ index.php?lang=en [NC,QSA] 

Of course I check the www redirect before this rule.

Thank you!!

like image 76
tobia.zanarella Avatar answered Sep 22 '22 13:09

tobia.zanarella