Canonical redirect on IIS using PHP

According to the seo experts of the world, it is good practice to force your website to always use the same domain. So, instead of having your site work at both www.example.com and example.com, choose one. Once you've chosen which form of your site to use, it's time to setup 301 redirects to enforce that.

If you're using Apache, it's very easy, just add a quick mod_rewrite rule. You can remove the www or force the use of www. But since IIS doesn't use .htaccess files, it takes a little more effort.

Create a php.ini with the following content and upload it to your site root

  1. [php]
  2. cgi.force_redirect = 0
  3. auto_prepend_file = C:\php_includes\canonical.php

Keep in mind that you'll need to change the file path to reflect the setup of your server.

Upload canonical.php with the following contents

  1. < ?php
  2. // Any directory index filenames should go in here with a leading /
  3. // This is removed when doing the redirect in order to maintain consistency,
  4. // without this, when visiting example.com you would be redirected to www.example.com/index.htm
  5. $index_files = array('/index.htm','/index.html','/index.php');
  6.  
  7. // The rewrite only kicks in if the host does not begin with www. and the code is not running
  8. // on localhost. When developing a site I setup dev.example.com on my dev machine and use
  9. // the same code as is on the live server, so I don't want to be redirected if I'm
  10. // accessing the code locally.
  11. if(substr($_SERVER['HTTP_HOST'],0,4) !== 'www.' && $_SERVER['LOCAL_ADDR'] !== '127.0.0.1'){
  12.     $url = 'http://www.'.$_SERVER['HTTP_HOST'].str_replace($index_files, '', $_SERVER['PATH_INFO']);
  13.     header ('HTTP/1.1 301 Moved Permanently');
  14.     header("Location: $url");
  15.     exit();
  16. }
  17. ?>

Notes: