|Ned Batchelder : Blog | Code | Text | Site|
Simple virtual hosts with PHP
» Home : Blog : September 2003
I chose my hosting provider based largely on price. I got the least expensive plan that would serve my purposes. One thing I did not buy was true virtual hosting, which is serving more than one web site from the same machine. I can park as many domains as I want on my account, but their home URLs all served the same page. Until I wrote this PHP script.
The idea is very simple, and is the sort of task that PHP excels at. Look at the browser's request to determine the host name requested. Then use that host name to choose the page to serve.
This doesn't provide true virtual hosting, it just makes the home URL of each parked domain serve different content. Pages within the hosts still overlap, so the URLs must be separated, for example, in subdirectories.
I'm no PHP expert, but I'm learning. For all I know, there are much simpler ways to do this. What I know is that this works, and I know why it works, so it was a good learning exercise.
Save this script as "index.php", and make sure "index.php" is served as the default page in your root directory. For example, on an Apache server, put these lines in your .htaccess file:
# Serving a directory should try these files in turn.
Now visiting your home page will load index.php, which will examine the host name requested, and serve different page content for each one.
tagged: php» react