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?
Asked
Active
Viewed 104 times
-3

php_nub_qq
- 15,199
- 21
- 74
- 144
-
You can do it by your web-server (like apache's htaccess or ngnix – undone Sep 24 '13 at 21:21
-
@JohnConde but this is the opposite of what I'm trying to do :/ – php_nub_qq Sep 24 '13 at 21:23
-
Is this about `Apache` ? – The Alpha Sep 24 '13 at 21:23
-
@SheikhHeera yes, I can use .htaccess but not really good at it – php_nub_qq Sep 24 '13 at 21:24
-
@php_nub_qq You can't use that as a guide to do what you want? It definitely tells you how to do it. – John Conde Sep 24 '13 at 21:24
2 Answers
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
-
Please forgive me for I am going to accept Sanja's answer but I believe he will enjoy 15 rep more than you will at this point. – php_nub_qq Sep 24 '13 at 21:29
-
1
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