Search code examples
phphttp-redirectno-www

PHP redirect for www to non-www with 301 on IIS


I'd like to get this straighten out once and for all:

<?php if ($_SERVER['HTTP_HOST'] != 'domain.com'){
header("Location: http://domain.com"
.$_SERVER['REQUEST_URI']);
} ?>

This will send all traffic to the NON-WWW version.

My question is - can I add 'header('HTTP/1.1 301 Moved Permanently');' safely without messing everything up?

I'm using IIS server so .htaccess is no good and all pages are coded in PHP - all solutions welcome.


Solution

  • Of course you can. Take advantage of all the parameters offered by header():

    <?php
    
    if ($_SERVER['HTTP_HOST'] != 'domain.com'){
        header("HTTP/1.1 301 Moved Permanently", true, 301);
        header("Location: http://domain.com".$_SERVER['REQUEST_URI']);
    }
    

    The last parameter is forcing the response code to be 301, as you want.