PHP: Always redirect to the non-www and https version of the current page

<?php
if(empty($_SERVER[‘HTTPS’]) || $_SERVER[‘HTTPS’] == “off”){ //check for non secure connections
$redirect = ‘https://’ . str_replace(‘www.’, ”, $_SERVER[‘HTTP_HOST’]) . $_SERVER[‘REQUEST_URI’];
header(‘HTTP/1.1 301 Moved Permanently’); //make a permanent redirect
header(‘Location: ‘ . $redirect);
exit();
}elseif(substr($_SERVER[‘HTTP_HOST’], 0, 4) === ‘www.’){ //check if the requested url begins with “www.”
$redirect = ‘https://’ . str_replace(‘www.’, ”, $_SERVER[‘HTTP_HOST’]) . $_SERVER[‘REQUEST_URI’];
header(‘HTTP/1.1 301 Moved Permanently’);  //make a permanent redirect
header(‘Location: ‘ . $redirect);
exit();
}

Leave a Reply

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