Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htacces rewrite tld without changing subdomain or dirs

I am trying to rewrite the following url:

the subdomain should match any subdomain. same for the TLD. both: http://car.example.com/ and http://cat.example.co.uk should be rewritten

http://subdomain.example.com/some/dir to http://subdomain.example.nl/some/dir

and http://example.com/some/dir to http://exampkle.nl/some/dir

(also with www. adress)

but my knowledge of htaccess and rewrite rules in general aren't good enough for this :(

I hope one of you knows the solution.

ps. I did try a search ;)

like image 620
Tjirp Avatar asked Mar 23 '11 13:03

Tjirp


1 Answers

The challenge comes with having to detect and account for four different possible domain patterns:

  • example.com → example.nl
  • example.co.uk → example.nl
  • sub.example.com → sub.example.nl
  • sub.example.co.uk → sub.example.nl

So, what this ruleset does is checks that the TLD is not .nl (preventing a loop from occurring), then pulls the subdomain, www or not, off the front (read as "capture anything other than a dot followed by a dot, optional), followed by the base domain, followed by a dot. We don't have to match the entire URL, since we aren't keeping the TLD.

RewriteEngine On
RewriteCond %{HTTP_HOST} !example\.nl$
RewriteCond %{HTTP_HOST} ^([^.]+\.)?example\.
RewriteRule ^ http://%1example.nl%{REQUEST_URI} [NC,L,R=301]

The RewriteRule's ^ matches any URL, then inserts the contents of the first set of parens in the preceding RewriteCond (the subdomain) with %1, and completes the rewriting by appending the requested path and flags to ignore case, make this the last rule, and redirect with a search-engine-friendly 301, ensuring the rewritten URL appears in the user's browser. Any query string (text appearing after a ? in the URL) is automatically included by default.

like image 64
Eric3 Avatar answered Sep 21 '22 19:09

Eric3