PHP Code
If you do not have the ability to create or modify your server settings, and use PHP to generate your pages, you can accomplish the same thing by adding a code snippet to the beginning of your scripts. The following code must be the first thing in the script, before any output is sent to the browser. Note that this code should work even if there is an internal mod_rewrite or other URL mapping or aliasing in place.
PHP Code:
<?php
if ($_SERVER['HTTP_HOST'] != 'www.yourdomain.com') { // First correct the domain issue
header('Location: http://www.yourdomain.com'.$_SERVER['REQUEST_URI'], 301);
exit();
}
if (eregi('/index.(html|htm|php)$', $_SERVER['REQUEST_URI'])) { // Then correct the directory root issue
$redirect = 'http://www.yourdomain.com'.eregi_replace('/index.(html|htm|php)', '/', $_SERVER['REQUEST_URI']);
header('Location: '.$redirect, 301);
exit();
}
?>
For simplicity, this could be added to a remote library script, and simply called by each PHP page on your site.
Handling HTTP and HTTPS
If you have HTTPS on your server, and do not want all of your content mirrored on both the HTTP and HTTPS versions, you can add the following lines to the top of every script, below the code I lay out above:
PHP Code:
<?php
$SHOULD_BE_SECURE = true; // This should be true if the file should be available over HTTPS, false otherwise.
require_once('/path/to/file/below.php');
?>
Elsewhere, create a PHP file with the following lines. This is the file that the require_once will point to.
PHP Code:
<?php
if (($_SERVER['HTTPS'] == 'off' && $SHOULD_BE_SECURE) || ) {
header('Location: https://www.yourdomain.com'.$_SERVER['REQUEST_URI'], 301);
exit();
}
if (($_SERVER['HTTPS'] == 'on' && !$SHOULD_BE_SECURE) || ) {
header('Location: http://www.yourdomain.com'.$_SERVER['REQUEST_URI'], 301);
exit();
}
?>
You could also add the code at the top of this post to this file, and have every file on your site call this script to check the URL and do the appropriate redirections.