Kaur Reinjärv
Kaur Reinjärv

Reputation: 35

Redirect alias TLD to lang param URL via htaccess

I managed to find solution but lost it and none of the others work at this point.

I'm interested in redirecting TLD such as example.fi, example.ru to domains with language parameter. For example URLs should become like this: Alias example.fi should be redirected to example.fi/?lang=fi which is the Finnish language homepage.

I've tried different options but none of them work.

I appreciate anyone who takes time to reply.

Upvotes: 1

Views: 205

Answers (1)

MrWhite
MrWhite

Reputation: 45948

Assuming:

  • You want to redirect any URL-path, not just the homepage (ie. root URL). (For homepage only see below*1.)
  • No other URL parameters are expected on the initial request.
  • If there is a conflicting lang URL parameter, eg. example.fi/?lang=de then the lang URL parameter is replaced. eg. a redirect to example.fi/?lang=fi occurs.
  • All domains are of the form example.<TLD> (or www.example.<TLD>). ie. no domains with a second level TLD like example.co.uk.

Try the following near the top of your root .htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?example\.([^.]+)
RewriteCond %{QUERY_STRING}@@%1 !^lang=([^.]+)@@\1$
RewriteRule (.*) /$1?lang=%1 [R=302,L]

The above redirects the following:

  • example.fi/ to example.fi/?lang=fi
  • example.fi/foo to example.fi/foo?lang=fi
  • example.fi/foo?lang=de to example.fi/foo?lang=fi
  • example.fi/foo?lang=fi&bar=1 to example.fi/foo?lang=fi

The %1 backreference contains the TLD from the requested hostname. This is used by the second condition to check that the appropriate ?lang=<TLD> query string is not already present in the query string. (This is achieved using an internal backreference \1 in the CondPattern.) If not then a redirect occurs to the same URL-path, but with the ?lang=<TLD> query string, overwriting any query string that might have previously been on the request.

This is currently a 302 (temporary) redirect. If this is intended to be permanent then change to a 301 (permanent) redirect only once you have confirmed that it works as intended.

*1 Homepage Only

If you specifically only want to append the lang URL parameter to the "homepage", ie. the root URL then change the RewriteRule directive to read:

:
RewriteRule ^$ /?lang=%1 [R=302,L]

Upvotes: 1

Related Questions