Some times it becomes important to add “www” to your site domain. There might be many more reasons to do so. I am just citing one example. Site name “domain.com” and “www.domain.com” are assumed to be two different sites by Google search engine robots. This will result in display of duplicate search results for your site. To avoid this problem you need to develop search engine friendly web pages.
These things can be better managed by setting rules in “.htaccess” files for application servers running on Apache and making some rule changes in higher versions of IIS(IIS 7). But when it comes to case of sites running on lower versions of IIS, it could be very difficult to handle all these. Recently I got into a problem as such and finally thought of writing my own code to append “www” to my site domain. That means if I write “domain.com” in browser URL bar, it will automatically redirect me to www.domain.com.
Put the code below in your onRequestStart method in Application.cfc and enjoy the same beauty of redirection easily.
/* Following code helps in redirecting "domains.com" to "www.domains.com" */
/* Get request from ColdFusion page contenxt. */
var objRequest = GetPageContext().GetRequest();
/* Get requested URL from request object. */
var strUrl = objRequest.GetRequestUrl().append("?" & objRequest.GetQueryString()).ToString();
var strUrl = objRequest.GetRequestUrl().ToString();
/* Replacing "http://" with "http://www."*/
if(NOT findNoCase("www", strUrl))
/*Checking whether the site URL uses "http" or "https"*/
if(compareNoCase(cgi.https, "off") EQ 0)
strUrl = replaceNoCase(strUrl, "http://", "http://www.","one");
strUrl = replaceNoCase(strUrl, "https://", "https://www.","one");
/* Forwarding to new url */
location( url="#strUrl#" addtoken="false");