I have done a lot of searching and have tried many things but I have still not managed to find a way of doing this exactly how I want it.

Without having to make an Apache VirtualHost for each subdomain, and either with apache2 (preferably), htaccess or DNS, I would like to redirect:

  • domain.xyz to domain.com
  • domain.xyz/* to domain.com/*
  • *.domain.xyz to *.domain.xyz (so a.domain.xyz goes to a.domain.com and b.domain.xyz goes to b.domain.com)
  • *domain.xyz/* to *.domain.com/*

What is the easiest way of doing this?


Approach 1

Disclaimer: I have not tried this first approach , but I think it might work.

<VirtualHost *:80>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^(.*)\.xyz$
    RewriteRule ^/(.*)$ http://%1.com/$1 [R=301,L]

So, the first RewriteCond should match the HTTP_HOST which will basically be your domain if it ends in .xyz. If it does, you just rewrite the request to the .com TLD with the same URI.

Approach 2

There's also another way. You could simply forward any request to a static PHP file, and place the original URL as a parameter to the script and once called, replace the URL to the domain you want. That would imply the following changes:

  1. Edit your apache's configuration and put something like this inside. This has been copied from here.

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !index.php
    RewriteRule .* index.php?url=$0 [QSA,L]

    This way, any request will be forwarded to a index.php file located wherever you defined in your DocumentRoot directive.

  2. In that file, you'd do something like this:

       $url =  "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
       $escaped_url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
       preg_match("/^http:\/\/(.*)\.xyz(.*)$/", $escaped_url, $matches);
       header("Location: http://{$matches[1]}.com{$matches[2]}");

    So you're just matching the original URL (stored inside $url) against a regexp and changing the location of the user (via the header()) function to the same domain but with different TLD. This last try has been tested and works well.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.