How to force www prefix in PHP and Asp.Net

How to prefix WWW to URL in PHP and ASP.NET

It is quite important to understand difference between URL prefixed with www and without www.

There seems to be not much difference in those as both represent same URL but this can be pain while coding some if its a bad day. It also make a difference in case of SEO and better to have uniformity in all URLs of website.

If you have adedicated server with IIS, its quite easy to force website to have each URL prefixed with www but in case of shared hosting you may be required to make some addition in code to acheive this. Here is a code snippet to force URL to prefix www in asp.net:

[code]
string scheme = HttpContext.Current.Request.Url.GetComponents(UriComponents.Scheme, UriFormat.UriEscaped);
string rightSide = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort | UriComponents.PathAndQuery, UriFormat.UriEscaped);

if (!rightSide.ToLower().StartsWith(“www.”) && !rightSide.ToLower().StartsWith(“localhost”))
{
HttpContext.Current.Response.Status = “301 Moved Permanently”;
HttpContext.Current.Response.StatusCode = 301;
HttpContext.Current.Response.AddHeader(“Location”, scheme + “://www.” + rightSide);
}
[/code]

Adding this to begin_request method in global.asax will solve the problem.

If same to be achieved in PHP, following code snippet should be helpful in .htaccess file:

[code]
RewriteEngine on
RewriteBase /

# Redirect to wwww
RewriteCond %{HTTP_HOST} !^www\.yourdomain\.com
RewriteRule (.*) http://www.yourdomain.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?/$1 [L]
[/code]

Deepak Sihag

Deepak is a Technical consultant, working on web since last 12 years. He excels in Microsoft .Net, OpenSource (mainly WordPress customization & plugin development) as well love working with CRM. He has been working with startups to listed companies and help them to build their online presence and reach target audience.

More Posts - Twitter - LinkedIn