Redirect a Website in ColdFusion – Add www. or Move to New Domain

ColdFusion, BabyRedirecting a website in ColdFusion (.CFM)

I have been working on a ColdFusion website, and I wanted to find a way to require ‘www.’ in the URL (to consolidate all pages on www. for SEO). I normally work with PHP and Apache servers, so I’m used to .htaccess. I knew there had to be a way.

Here’s a simple method of redirecting a whole website in ColdFusion:

<!-- If the site isn't www... -->
<cfif (CGI.SERVER_NAME NEQ "www.example.com")>
<!-- Save the URL (and $_GET variables too) as the string 'strUrl' -->
<cfset strUrl = CGI.script_name & "?" & CGI.query_string />
<!-- Use 301 for SEO-friendly redirects -->
<cfheader statuscode="301" statustext="Moved permanently">
<!-- Redirect to new website (this case, added www.) with strUrl added on -->
<cfheader name="Location" value="http://www.example.com#strUrl#">
</cfif>

Here’s how to redirect a single page in ColdFusion:

This code is real easy to find online, so the post was mostly to deal with the site-wide redirect…but here’s the single page code. Add this code to the top of the page you’d like to redirect from. Learn more about cfheader here.

<cfheader statuscode="301" statustext="Moved permanently">
<cflocation url="http://www.example.com/new-page.cfm">

Redirect with HTTPS sensativity

There are additional methods of checking whether or not HTTPS is active.
<cfif (CGI.SERVER_NAME EQ "www.example.com") AND (HTTPS Is "on")>
<!-- If is HTTPS and not www. -->
<cfelseif (CGI.SERVER_NAME EQ "www.mcstech.net") AND (HTTPS Is "off")>
<!-- If is HTTP and www. -->
<cfelse>
<!-- If is HTTP and not www. -->
</cfif>

Thanks to Ben Nadel’s Blog for the helpful ColdFusion resources.  Let’s hope I stick around PHP in the future :-)

This entry was posted in Tutorial, Web Development and tagged , , , , , . Bookmark the permalink.
  • ilowelife

    Thanks very much for this tip. Saved me digging around all over the place for the answer.

    While we’re at it, any idea how to display a brief message about the change for a few seconds, then proceed with the redirect?

  • Anees

    Thanks for your post

    but i doubts where i should paste this code for ‘whole redirection’
    do you says that i need to paste on the top of all the pages in the site
    i mean what is the .htaccess equilant file in this  folder

    • http://www.seodenver.com Zack Katz

      Normally, you would have a file that is included on every page; a global file. That’s where you put this.