Web Hosting Talk







View Full Version : Converting www.example.com to example.com automagically


Dan L
03-23-2006, 03:17 PM
$domain = $_SERVER['SERVER_NAME'];
$pathinfo = $_SERVER['REQUEST_URI'];
if(eregi('www.',$domain)) {
$domain = ereg_replace('www.','',$domain);
header('Location: http://'.$domain.$pathinfo);
}That's all there is to it. Just put this code in your index.php file, and it will check whether the www. prefix is used or not. Everything from there is taken care of by the script itself.

Enjoy :)

Darkstarx
05-29-2006, 02:52 AM
Using "eregi" is probably not the most efficient way to go about this. There are lighter-weight "String Search" functions in PHP. Also, this is probably best done at httpd level, using a .htaccess file or such.

Jatinder
05-31-2006, 03:26 AM
I think a simple str_replace should be more efficient


<?php
$domain = $_SERVER['SERVER_NAME'];
$domain=str_replace('www.','',$domain);
?>

Commit1 Robert
06-09-2006, 02:20 AM
If you have decided to use _SERVER, then simply call the "HTTP_HOST".


<?php
$domain = $_SERVER['HTTP_HOST'];
echo $domain;

//Outputs: domainname.com

Jatinder
06-09-2006, 02:23 PM
If you have decided to use _SERVER, then simply call the "HTTP_HOST".


Won't work. You will still need to replace the "www." part.

laserlight
06-09-2006, 03:17 PM
Won't work. You will still need to replace the "www." part.
Still not perfect though. Consider:
<?php
$domain = 'www.example-www.com';
$domain = str_replace('www.','',$domain);
echo $domain;
?>

If I really wanted to do this in PHP, I think I might use:
$domain = preg_replace('/^www\.(.*)/i', '\1', $domain);

Darkstarx's idea of configuring the server or using a .htaccess file (if using Apache) is probably best.

Shayan
01-04-2008, 01:05 AM
I am aware of the fact that this topic is extremely old however I believe that this useful peace of information may help many people who still need assistance doing this. The easiest and most efficient way of removing www from the URL would be to copy the following code into your .htaccess replacing the red text with your own websites information:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ ht tp://domain.com/$1 [R=301,L]


IMPORTANT: On line three remember to delete the space between ht tp://
I was forced to enter a space due to the fact that I do not have five posts and therefore cannot post links.


To the WHT Staff, if you feel that this bump is unnecessary than by all means delete the post and I am sorry for the inconvenience.

superprogram
01-04-2008, 02:16 AM
What advantage does removing of www from the url has?

Shayan
01-04-2008, 04:04 AM
The reasoning for removing www from the URL is as follows:
By default, all popular Web browsers assume the HTTP protocol. In doing so, the software prepends the 'ht tp://' onto the requested URL and automatically connect to the HTTP server on port 80. Why then do many servers require their websites to communicate through the www subdomain? Mail servers do not require you to send emails to recipient@mail.domain.com. Likewise, web servers should allow access to their pages though the main domain unless a particular subdomain is required. Succinctly, use of the www subdomain is redundant and time consuming to communicate. The internet, media, and society are all better off without it.

Yet again I have put spaces in between the ht and tp due to the fact that I cannot post links.

focusinterview
06-24-2008, 04:30 AM
Ahhh!!


I think this can also be done via apache's .htaccess

chadsayad
07-04-2008, 09:40 PM
CHEERS M8 thanks ,

HostGreen
08-03-2008, 11:59 AM
Here's a similar script you may find useful... I can't remember where it originated from unfortunately. I think php.net

function getHostNamefromURL($url) {
// get host name from URL
preg_match('@^(?:http ://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
return $matches[0];
} (remove the space between http and :// - wht won't let me post it otherwise)

Basically,
echo getHostNamefromURL("mail.google.com/mail"); // will echo "google.com"
echo getHostNamefromURL("news.yahoo.cn"); // will echo "yahoo.cn"

Hope it helps somebody.

Nick_R
08-09-2008, 12:35 PM
Thanks for this :)

desaid
09-11-2008, 08:30 AM
Thanks guys

Young Coder
04-13-2009, 09:22 AM
is this better than using .htaccess , i mean for google and others search engines ?

thanks

#fdd700
04-13-2009, 08:41 PM
is this better than using .htaccess , i mean for google and others search engines ?

thanks

Both send 301 (or 302) redirect to a browser/bot, so they are the same in the eyes of Google and the others. .htaccess is the proffered solution though as it eliminates an unnecessary launch of php script and kicks off one step earlier. Also, 301 is better in many cases.

`Jonathan
04-22-2009, 02:53 PM
On my opinion this is another way on how to do it <?php header('Location: http://www.domain.com/'); ?> name the file index.php

HTTP404
04-23-2009, 11:16 AM
Whats the point in this? It goes to the same document anyway, its just if your users type www or not?

Sorry, But correct me If I am wrong.

mwatkins
04-23-2009, 11:51 AM
Why? A guiding principle for the web is there should be one and only one URL to a specific resource / page.

www.example.com is not necessarily the same host as example.com. People view domains as being ethereal but at some point there is a physical reality. While we all assume that www|no www point to the same place, how about webmail.example.com and example.com/mail ?


Additionally, some also don't like the www prefix; others like it. Personally I do not favour the www prefix myself; the web is so common now that people simply assume you are referencing a web site if you speak the domain outloud, so there's no need to hear or think about "double u, double u, double u dot".

Since it is easy to do the redirection at the http server level rather than in code, there really is no reason not to make a policy decision and adopt one or the other. It's also a lot more efficient to do it at the httpd level rather than in PHP or what have you.

To go along with the Apache example provided up thread, here's the redirect rule for the lighttpd (http://www.lighttpd.net/) web server:

$HTTP["host"] =~ "^www\.(.*)$" {
url.redirect = ( "^/(.*)" => "http://%1/$1" )
}

where:


%1 - is the value obtained in the conditional expression (part of the equivalency test on the first line, in red) - this will contain the hostname without "www.", and
$1 - is replaced by the first (and only in this case) regular expression match "(.*)" (in purple) which is of course the full path following the hostname.

HTTP404
04-23-2009, 01:30 PM
True, doing it through .htaccess is better than in code, if not you'll have to add the code to all pages, plus its slower, through .htaccess it will effect all files even images, if you do it through PHP, you'll have to add the lines to every piece of code if you want to drop or add the WWW site wide.

ramnet
04-23-2009, 04:24 PM
Using "eregi" is probably not the most efficient way to go about this. There are lighter-weight "String Search" functions in PHP. Also, this is probably best done at httpd level, using a .htaccess file or such.

Or you could do it the retro way like this:


/* redir.c */
/* unconditionally redirect an entire host to another */
/* preserves things in REQUEST_URI so you can move a site without breaking links */
/* usage: put this in .htaccess
SetEnv REDIR_TO_HOST example.com
ErrorDocument 404 /index.cgi
*/
/* to redirect an entire domain from whatever this host is to the host specified in REDIR_TO_HOST */
/* compile with:
gcc -o index.cgi redir.c; strip index.cgi
*/
/* C is very fast for simple things like this */

#include <stdio.h>
#include <stdlib.h>

int main()
{
char *redir_to;
char *redir_from;

redir_from=getenv("REQUEST_URI");
redir_to=getenv("REDIR_TO_HOST");

if(redir_from==NULL)
{
/*
printf("Content-Type: text/html\n");
nocache();
printf("\n");
printf("<p>Error! Something wrong with server - could not get REQUEST_URI</p>\n");
*/
redir_from="/";
}
if(redir_to==NULL)
{
printf("Content-Type: text/html\n");
nocache();
printf("\n");
printf("<p>Error! Something wrong with .htaccess - REDIR_TO_HOST not set</p>\n");
}
else
{
printf("Content-Type: text/html\n");
printf("Status: 301\n");
/* disable following line if everything works well */
nocache();
printf("Location: http://%s%s\n",redir_to,redir_from);
printf("\n");
}
return 0;
}

int nocache()
{
printf("Expires: -1\n");
printf("Cache-Control: no-store,no-cache,must-revalidate\n");
printf("Pragma: no-cache\n");
return 0;
}



Whew. That really takes me back! I've attached the above source along with a compiled executable (build on debian 4.0) and sample .htaccess. Enjoy!

10gbus
05-15-2009, 06:09 AM
Hi
thanks for sharing.

AaliyahRoma
05-29-2009, 11:36 AM
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]


http://www.cafewebmaster.com/redirect-webpages-html-php-htaccess-javascript-cgi-perl-aspnet-and-coldfusion

WRZHost[dot]com
01-12-2010, 05:23 AM
Thanks,

Just found it but works a treat :)

SpaceWalker
01-26-2010, 08:21 PM
I wonder what's the point behind this, Why would you need to remove 'www.' from the site name ?

by default most control panel (when adding a new domain) creates CNAME (dns entry) that points to the original domain.

So most websites works as expected with or without the www prefix.

unless otherwise you have added the dns entries manually at your registrar company then you don't need this hack & even so ,if you did not link the www. as a CNAME "as it should be" there's no way to move visitors away to the normal domain (they'll get dns error)

The only advantage I can think of, is cookies domain, if that's the case then good luck.

ramnet
01-28-2010, 01:34 AM
I wonder what's the point behind this, Why would you need to remove 'www.' from the site name ?


Off the top of my head:

1) Cookies

2) Caching

3) Search Engines

I'm sure there are others :)

Unknow
03-08-2010, 03:10 AM
Thanks ;-)

|NaturalHost|
03-15-2010, 01:42 AM
Thanks for the tutorial :)

Cyber404
03-15-2010, 03:15 AM
Thanks for the tut, it's really helpful!

anjo2
04-05-2010, 05:45 PM
$domain = $_SERVER['SERVER_NAME'];
$pathinfo = $_SERVER['REQUEST_URI'];
if(eregi('www.',$domain)) {
$domain = ereg_replace('www.','',$domain);
header('Location: http://'.$domain.$pathinfo);
}That's all there is to it. Just put this code in your index.php file, and it will check whether the www. prefix is used or not. Everything from there is taken care of by the script itself.

Enjoy :)

$domain = $_SERVER['SERVER_NAME'];
$pathinfo = $_SERVER['REQUEST_URI'];
if(eregi('www.',$domain)) {
$domain = ereg_replace('www.','',$domain);
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://'.$domain.$pathinfo);
}
Due to crawlers it's better to put a 301 redirect, www is only a subdomain, very used, but can be seen as an other site.

larwilliams
04-05-2010, 06:41 PM
If you are using Apache as your web server, simply add the following to a .htaccess file in the same folder as your site pages

Replace example.com with your domain name.


RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

ramnet
04-05-2010, 06:52 PM
$domain = $_SERVER['SERVER_NAME'];
$pathinfo = $_SERVER['REQUEST_URI'];
if(eregi('www.',$domain)) {
$domain = ereg_replace('www.','',$domain);
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://'.$domain.$pathinfo);
}Due to crawlers it's better to put a 301 redirect, www is only a subdomain, very used, but can be seen as an other site.

Excellent advise.

However sending "HTTP/1.1 301 Moved Permanently" may not always work for a variety of reasons (apache vs something else, cgi vs fastcgi, linux vs windows, etc) -

eregi and excess variables are unnecessary (and ereg is depreciated anyway).

This is what I would use to ensure it all works as expected if you're using the PHP method:


if(strstr($_SERVER['SERVER_NAME'],'www.')!=false)
{
header('Location: http://'.str_replace('www.','',$_SERVER['SERVER_NAME']).$_SERVER['REQUEST_URI'],true,301);
}
That's far better on performance then firing up the regex engine , and sends a 301 redirect in the correct PHP manner :)

Works with PHP 4.3.0+, PHP 5 (all, including 5.3.x), and PHP 6 :)

larwilliams
04-05-2010, 07:05 PM
I see 20 PHP-based solutions, when my simple .htaccess would be the best performance-wise and compatibility.

ramnet
04-05-2010, 07:14 PM
I see 20 PHP-based solutions, when my simple .htaccess would be the best performance-wise

Agreed. If you're using Apache.


and compatibility.
Requires Apache (or LiteSpeed) - lots of people using Nginx, Lighttpd, IIS, and others these days - that doesn't work for them ;)

---

Really, this is something that should be configured at the web server daemon level rather than the site level - put that in httpd.conf and turn off .htaccess is you're using Apache and care about performance (although if you're still using Apache you prolly don't care much about performance anyway :P).

anjo2
04-05-2010, 08:15 PM
With .htaccess is the better, but in the most cases php is more easy for all people, and works in "all" servers (the most servers have php).

lcdstap
04-08-2010, 09:47 PM
You would want to remove www. perhaps if you were calling that domain via code, keep your domains neat... otherwise for SEO someone above said that was a good reason to remove www., that seems a little silly to me...

HTTP404
04-09-2010, 04:49 AM
I never use the www prefix on domains, does this matter?

siros
04-11-2010, 07:57 AM
If you are using Apache as your web server, simply add the following to a .htaccess file in the same folder as your site pages

Replace example.com with your domain name.


RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]



It seems to be the easiest way for me instead of making changes to php files.


but am not sure if it's going to make server loads higher because I added some VBSEO codes to my .hatacces file and it is making server loads high because of the rewriting rules , but I removed it along with the VBSEO plugin , I was lucky enough to figure out this before it's too late to remove the plugin :D

I have been facing lots of troubles with www at the beginning of the domain.

but when I logged in into my forums . The ( www ) disappeared :D


any ideas :) ?


Thank you for sharing ;)

aspire7
05-12-2010, 11:02 AM
This stuff helps with seo, although i prefer to change domainname.com to www.domainname.com Maybe it is better the other way.

anjo2
05-12-2010, 12:21 PM
This stuff helps with seo, although i prefer to change domainname.com to www.domainname.com Maybe it is better the other way.

It's the same.

Korvan
05-13-2010, 04:47 PM
Its preference whether you want to have your website mainly hosted on www.example.com or just example.com as long as you have valid dns records for both you can redirect one to the other. Or as many different subdomains you want. The only thing is that when people manually enter your web address they are more likely to type www.example.com than just example.com, and it might reduce the load on your server by a few milliseconds if your webserver operated off of www and just forwarded the empty subdomain. Any time you forward with an header it means the remote client will have to send another GET request to the server, which could mean for them (depending on their bandwidth, and line quality) a noticable difference in load times.

And hey look at that this web forum will automatically parse www.example.com into a link while it does not parse example.com into a link. Things like this can make forcing to www more advantagous.

Dorkslayz
06-02-2011, 02:27 PM
Can you extend the script a bit? Like make it query a DB and see where the DB tells www to go to, That would make it easier for creating subdomains.

anjo2
06-02-2011, 11:55 PM
This work with www due to the most servers have a type A for www
www A 127.0.0.1
When you create a subdomain, you create a dns entry
subdomain A 127.0.0.1
It is not easy at all...

uswah
06-09-2011, 10:34 AM
thanks for the informative post

riceboi1230
06-11-2011, 12:20 PM
Or you can put it in your .htaccess file.