-3

I want to detect if users who enter my site have entered the www subdomain, which most wont, and in such case redirect them to www. Basically if a user enters mysite.com I need to redirect them to www.mysite.com but I don't see how this can be detected with PHP only? My $_SERVER array doesn't contain such information. Is this possible at all?

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144

2 Answers2

2

You may try this using Apache mod rewrite (put it in .htaccess file)

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
The Alpha
  • 143,660
  • 29
  • 287
  • 307
1

Worse solution is to do it with PHP:

if (substr($_SERVER['SERVER_NAME'], 0, 4) !== 'www.') {
  header('Location: http://www.' . $_SERVER['SERVER_NAME']);
  exit();
}

Better from performance point of view solution with .htaccess:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Alex
  • 1,605
  • 11
  • 14