Performing a mod_rewrite style "Require www." redirect in PHP only?

How would one go about performing the equivalent of mod_rewrite style forced www redirection in PHP only (sans mod_rewrite)?

Where the equivalent mod_rewrite code is for instance:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\\.askapache\\.com$ [NC]
RewriteRule ^(.*)$$1 [R=301,L]

if ($_SERVER['HTTP_HOST'] != '') {
  header("Location:" . $_SERVER['REQUEST_URI'], true, 301);

Thanks :slight_smile: So if one wanted to make this be able to handle an arbitrary subdomain, including forcing no www, it would be something like this?:

$prefix = ''; // e.g. 'www.', 'widgets.'
$domain = '';
if ($_SERVER['HTTP_HOST'] != $prefix . $domain') {
  header("Location: http://" . $prefix . $domain . $_SERVER['REQUEST_URI'], true, 301);