03.07.07
Using .htaccess to map several domain names to a single site
A disclaimer before we start: .htaccess can do wonderful things for your website as long as the web server that runs it is Apache! The ideal environment would be Linux and Apache but the concept is supported on NT/Windows 200x implementations of Apache.
First, what is it? .htaccess is a text file that is placed in the root of your web site to control how the Apache web server daemon interprets requests from users’ browsers. It works as the configuration file for Apache’s Mod_Rewrite module and deals with, amongst other things, the password protection of specific pages, directories or the whole site. It also determines what pages are served when particular requests are received:
Options +FollowSymlinks
RewriteEngine on
rewritecond %{REQUEST_FILENAME} ^(.+)\.zip$
RewriteRule ^(.+)$ / [nc]
These cryptic lines of text simply take the visitor to your home page every time they request a file with a .zip extension. Replace ‘zip’ with any other extension (e.g. jpg) that you want to keep private. You can save the above as .htaccess in the root of your site or inside a directory that contains zip archives that you don’t want visitors to access.
My main use of .htaccess is mapping several domain names onto different directories of the same web site. For instance, you’ve bought d1.com, d2.com, d3.com. You only want to pay for the hosting of one web site, let’s say d1.com. Provided your domain name broker lets you set the IP address of each one of your domains, you can do the following:
- Set up your website for d1.com using your hosted space.
- Set the IP addresses of d2.com and d3.com to the address of d1.com
- Create directories d2 and d3 off the root of your d1.com site.
- ftp the websites for d2.com and d3.com into these directories. You can check them by directing your browser to: http://www.d1.com/d2 or http://www.1.com/d3
- Make sure that the root of d1.com contains a robots.txt file with at least the following lines:
User-agent: *
Disallow: /d2/
Disallow: /d3/
Create (or edit) the .htaccess file in the root of your main website:
Options +FollowSymlinks
RewriteEngine onRewriteCond %{HTTP_HOST} ^(.*)d2\.com [nc]
RewriteRule ^(.*)$ http://www.d1.com/d2/$1 [P,nc]
RewriteCond %{HTTP_HOST} ^(.*)d3\.com [nc]
RewriteRule ^(.*)$ http://www.d1.com/d3/$1 [P,nc]
Now, http://www.d2.com will serve out the pages found in www.d1.com/d2 although the user’s browser will still display www.d2.com in the address bar.
A great resource for unravelling many of the secrets of .htaccess files and the mod_rewrite module is: