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]

I am a Technical consultant with over 16 years of experience in developing, leading, and consulting on various web and mobile applications for startups and businesses. My core competencies include open-source frameworks, PHP, Marketo, WordPress and Digital Marketing Strategy. I am also a certified Microsoft Professional and a graduate of the Executive Program in Digital and Social Media Marketing from IIM Raipur. I lead a team of talented and passionate developers, designers, and marketers who deliver innovative and impactful solutions for our clients. We work with the latest technologies and methodologies, such as AI, cloud computing, agile, and DevOps, to create user-friendly, scalable, and secure products that meet the needs and expectations of our customers.

More Posts - Twitter - LinkedIn - Google Plus