Search code examples
apache.htaccessmod-rewriteurl-rewritingmultilingual

How to configure multiple languages via htaccess and sub domains as a GET method?


I want to design my website to have multiple languages and I need to implement it as subdomains. For example:

https://www.example.com/
https://fa.example.com/
https://en.example.com/

So as I searched and found there are different options.

  1. I should copy my website in different subdomains and change it's language.
  2. Use Url rewriting via htaccess for changing language.

Please guide me which one is a better option.

And if i want to use the second option how i can write it in htaccess.

Note that in second option I need this kind of rewritings:

For example:
https://en.example.com/
will be :
https://www.example.com/?lang=en

or

https://en.example.com/login/
will be:
https://www.example.com/login/?lang=en

or

https://en.example.com/login/example.php?a=123
will be:
https://www.example.com/login/example.php?a=123&lang=en

and all other urls also will change like this.

PS: My site is only available on https by this code:

RewriteEngine On
Options +SymLinksIfOwnerMatch

RewriteCond %{SERVER_PORT} 80 
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


rewritecond %{http_host} ^example.com [nc]
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
rewriterule ^(.*)$ https://www.example.com/$1 [r=301,nc]

Thanks for your help


Solution

  • Copying whole website in multiple directories is not a good idea as you have to maintain and modify files in multiple locations.

    Translating language prefix of domain name as lang parameter should be a preferred option.

    You can create a wildcard VirtualDomain and point all the subdomains to same DirectoryRoot. Then you can have following rules in site root .htaccess:

    Options +SymLinksIfOwnerMatch
    RewriteEngine On
    
    # http => https
    RewriteCond %{SERVER_PORT} 80 
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
    
    # add www to main domain
    RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
    RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
    RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
    RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L,NE]
    
    # language subdomains handler
    RewriteCond %{QUERY_STRING} !(?:^|&)lang= [NC]
    RewriteCond %{HTTP_HOST} ^([a-z]{2})\.
    RewriteRule ^ %{REQUEST_URI}?lang=%1 [QSA,L]