Using cfheader to redirect content in ColdFusion

I just thought I’d share  a few things I discovered about doing content redirection with cfheader to save you the time it took me to get this to work.

I recently had a need to improve my website’s handling of missing pages following a large content overhaul. I didn’t just want to use one file for all 404 errors. Instead, I wanted to properly handle permanent redirects, deleted content, and other changes that may impact users who had links to old content. Since we use ColdFusion 8, we are using the application.cfc file along with the onMissingTemplate function to handle these redirects for the entire site. Most examples I’ve seen use ColdFusion’s cflocation tag to redirect the page request; however, this was not the ideal option because it only allows setting of the http status code to one of the 3xx codes. This is OK for a temporary or permanent redirect but not really correct for a redirection to an error page.

Since SEO best practices dictate that you use status code 404 for cases where the cause of the missing page is unknown and instead use the most appropriate code  based on the status of the page, I set out to find information about how to do redirects using the cfheader tag. What a headache! Most examples out there suggest, incorrectly, that you just need to add something like this to the handler:

Wrong:

  <cfheader statuscode="410" statustext="Gone">
  <cfheader name="Location" value="/removed.cfm">

I spent tons of time trying to figure out, rather unsuccessfully, why this code did not work. No matter what I tried, I could not get the browser to redirect to the error page. Finally, after much testing and trying different things, I found what I was looking for on Pete Freitag’s blog. I was missing an important tag to get this to work: the cfabort tag. The correct code is as follows:

Right:

 
  <cfheader statuscode="410" statustext="Gone">
  <cfheader name="Location" value="/removed.cfm">
  <cfabort>

If you plan to implement something like this, it helps to know some of the most useful http codes. Below is a list of examples for some of the most common codes. For a complete list of http status code, I suggest you go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.

Permanent Redirect:

 
 <cfheader statuscode="301" statustext="Moved Permanently"> 
 <cfheader name="Location" value="/moved.cfm">
 <cfabort>
  

Temporary Redirect:

 <cfheader statuscode="307" statustext="Temporary Redirect"> 
 <cfheader name="Location" value="/temp.cfm">
 <cfabort>
   

Content Permanently Removed:

  
 <cfheader statuscode="410" statustext="Gone">
 <cfheader name="Location" value="/removed.cfm">
 <cfabort>
 
Advertisements

Posted on April 27, 2011, in ColdFusion, Programming and tagged . Bookmark the permalink. Comments Off on Using cfheader to redirect content in ColdFusion.

Comments are closed.

%d bloggers like this: