Andreas Jarbol
Andreas Jarbol

Reputation: 745

Rewriting the domain extension

I have a website with multiple domain extensions:

example.com
example.de
example.fr
example.co.uk

I would like for people to get redirected to the .com domain so that the the urls are rewritten as follows:

example.de        -> http://www.example.com/?loc=de
example.fr        -> http://www.example.com/?loc=fr
www.example.co.uk -> http://www.example.com/?loc=uk

However, I don't know how to select the domain extension part of the URL example.(fr)/bla and rewrite. I realize that I could create special cases for each ex.:

RewriteCond %{HTTP_HOST} !^(www\.)?example\.de$
RewriteRule .* http://www.example.com/?loc=de [L,R=301]

However I would like to make it so that if I buy more extensions, that I wouldn't need to update the httpd.conf file etc.

Any suggestions are appreciated!

Upvotes: 2

Views: 962

Answers (1)

icabod
icabod

Reputation: 7074

It's quite simple to create a rule that covers several domains. To achieve what you want, you could do something like this:

RewriteCond %{HTTP_HOST} ^(www\.)?example\.(de|fr|co\.uk)$
RewriteRule .* http://www.example.com/?loc=%2 [R]

It takes example.de and rewrites it as example.com/~loc=de as requested, and works also for .fr, and .co.uk. However a caveat is that it rewrites the .co.uk version as example.com/~loc=co.uk, which isn't quite what you want. It would also need to be modified for new domains.

So, here's a solution that's a little more generic, but should achieve what you want:

RewriteCond %{HTTP_HOST} ^(www\.)?example\.(co\.)?(.*)$
RewriteCond %{HTTP_HOST} !^(www\.)?example\.com$
RewriteRule .* http://example.com/?loc=%3 [R]

Now a little explanation:

The first RewriteCond matches any domain with example in it, such as example.co.uk, www.example.de, www.example.xxx, etc.

The second RewriteCond makes sure that the HTTP_HOST isn't example.com or www.example.com.

Finally the RewriteRule rewrites anything that matches those two rules, and sticks the last part of the domain onto the end as a parameter.

http://www.example.co.uk/ -> http://example.com/?loc=uk

http://www.example.de/ -> http://example.com/?loc=de

http://www.example.xxx/ -> http://example.com/?loc=xxx

http://www.example.com/ doesn't redirect.


Note that in the solutions above, if the user went to http://www.example.de/some/path/index.php, the path would not get redirected. If you want this functionality, then we need to include the path in the redirection:

RewriteRule (.*) http://example.com/$1?loc=%3 [R]

Upvotes: 3

Related Questions