Multilanguage subdomain mod_rewrite

Hello,

I am in the process of setting-up multi language support for my website. Currently everything works when I add the appropriate parameter in the URL. For example:
domain.com?lang=fr or domain.com?lang=es or domain.com/product?lang=fr

However, instead of constantly adding “?lang=fr” or “?lang=es” , depending on the language, I would like to do it via subdomains.

So, I have created two subdomains on the server

fr.domain.com which points to domain.com/fr
and es.domain.com which points to domain.com/es

When I go to fr.domain.com I want the equivalent of going to domain.com?lang=fr

So far I have the following in my htaccess for the fr subdomain, which somewhat works:

(this htaccess is located in the “domain.com/fr/” directory

RewriteEngine on
RewriteRule ^ https:/domain.com?lang=fr [L]

So this redirects “fr.domain.com” to “https:/domain.com?lang=fr” and so it works partially. I want to keep “fr.domain.com” in the browser URL bar, not sure how to do this?

Big problem is that the above doesn’t work for any subpages, such as “fr.domain.com/product

So I tried the following:

RewriteEngine on
RewriteRule ^ https://domain.com%{REQUEST_URI}&lang=fr [L]

However, neither of these 2 methods keeps “fr.domain.com” in the browser bar.

Any help would be much appreciated!

It would be a lot easier to let your software that’s running behind Apache base the language used on the (sub)domain rather than a query parameter.

For instance, if this is PHP, rather than looking at $_GET['lang'] look at $_SERVER['HTTP_HOST'] to find out which language should be used.

i.e.

$subdomain = explode($_SERVER['HTTP_HOST'], '.')[0];
$language = $subdomain === 'domain' ? 'en' : $subdomain;

This is brilliant - thank you!

To others who may have this issue, I have set the language domains to point to the root (public_html) directory. Then I utilized rpkamp’s code, and everything works perfectly.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.