A simple way to correct the hostname for your website

There are several ways to force the correct hostname on a website. Normally this is done with mod_rewrite within the vhost or within the .htaccess file (if allowed). However there is a very simple way to do it with PHP. All you need to do is check that the value of $_SERVER[‘HTTP_HOST’] matches the domain name you want your site to work under.

<?php

$host_name   = $_SERVER['HTTP_HOST'];
$request_uri = $_SERVER['REQUEST_URI'];

$correct_host = 'www.example.com';

if ($host_name != $correct_host) {
header ('HTTP/1.1 301 Moved Permanently');
header ('Location: http://' . $correct_host . $request_uri);
exit;
}
?>

As you can see the above code checks to see what the host name is for the request. If the hostname is not the desired one then a 301 redirect occurs to the correct host name. My example only covers http requests, if you want to use the same code on ssl and non ssl requests then you will need to check for the presence of $_SERVER[‘HTTPS’] or you can check to see if $_SERVER[‘SERVER_PORT’] is 443.

If you intend to use this code then it needs to be placed as early in the execution of your script. If you are using a frame work such as symfony then if can be added to a filter.

A good time to use this code is when you want to force all of your traffic to use http://www.example.com and not http://example.com, or if you have multiple domains pointing to the same vhost and want to forward all the visitors to your preferred domain.

3 thoughts on “A simple way to correct the hostname for your website”

  1. Don’t forget the exit; after the Location header 🙂 Otherwise it will continue to execute code until it exits on its own.

  2. If it is possible to do this using mod_rewrite you should go for it. Doing so will eliminate the overhead of starting the PHP engine.

Leave a Reply

Your email address will not be published. Required fields are marked *