Welcome to WebmasterWorld Guest from

Message Too Old, No Replies

What code can we use to redirect non-www to www



8:38 am on Oct 25, 2005 (gmt 0)

10+ Year Member

What code can we use to redirect non-www to www on a page that would work. PHP and an ASP VBScript would be useful for anyone on Windows hosting who don’t have access to the server control.

In C it would look something like this:

string url = Request.RawUrl;

if (url.IndexOf("http://www") >= 0)
url = "http://www" + url;


2:32 pm on Oct 25, 2005 (gmt 0)

10+ Year Member


if (!preg_match("/^www.example/i",$_SERVER[HTTP_HOST]) ) {
header("HTTP/1.1 301 Moved Permanently");
if (strlen($_SERVER['QUERY_STRING'])>0)
else if ($PHP_SELF=="/index.php")


3:12 pm on Oct 25, 2005 (gmt 0)

10+ Year Member

The C code above applied to ASP results in a 302 response, because the method Response.Redirect(location) does that by default. This code (from the top of my head, not tested) should do the trick if you suffer from Windows:

DIM url,server
server = "www.example.com"
' add more if the URI contains a query string:
url = "http://" & server & Request.ServerVariables("URL")
if Request.ServerVariables("SERVER_NAME") <> server then
Response.Status = "301 Moved Permanently"
Response.AddHeader "Location", url
end if

If you have a real host, put this in your root's .htaccess file and don't bother with redirects in scripts:

# redirect permanent domain.tld/* to www.domain.tld/*
RewriteEngine On
RewriteCond %{HTTP_HOST}!^www\.example\.com [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]


4:02 pm on Oct 25, 2005 (gmt 0)

10+ Year Member

I have both PHP and ASP (VBScript) running off a Windows server with no access to .htaccess

The ASP sites are fixed but with PHP I dont really know at all I keep getting:

Parse error: parse error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\.....Line 6 (that line 5 in the PHP sample in the above post).


4:07 pm on Oct 25, 2005 (gmt 0)

WebmasterWorld Senior Member encyclo is a WebmasterWorld Top Contributor of All Time 10+ Year Member

For the parse error, the above is missingf a semi-colon at the end of the line:

else if ($PHP_SELF=="/index.php")[red];[/red] 

Featured Threads

Hot Threads This Week

Hot Threads This Month