Using ColdFusion to Handle HTTP 404 Page Not Found Errors

This article will not address the onMissingTemplate method which only runs when a CFML page does not exist (i.e., wwwroot/directory/thisPageDoesNotExist.cfm). In addition, this article will not address using custom headers or a .htaccess file with Apache. This article will address those other "page not found" errors often found in Windows hosted environments.

Let's start by assuming someone tries to visit www.yourdomain.com/thisDirectoryDoesNotExist, or www.yourdomain.com/thisPageDoesNotExist.html and neither the directory, nor the page actually exist on your site. Or, better yet, you've just spent months building a new, dynamic site for a client using ColdFusion and their old site was an old, yucky plain HTML site with pages everywhere. Now, your client, who's a little savvy in the SEO department, (that's search engine optimization for you non-seo-knowing folk), has requested you setup redirects for each of his old pages to the new ones you've created.

If you're anything like me, I used to dread the thought of taking care of this. I used to spend a ton of time on this by creating a separate page for each of the "old" pages and directories, then using either JavaScript to handle the redirects (if the old page was vanilla HTML) or the "old" dynamic language (i.e., ASP, PHP, etc.) to create custom headers, etc. Regardless, it was a major pain to do this, especially because it cluttered my site with a bunch of extra files that were essentially useless.

Then, I had one of those "light bulb moments." I thought, "Hey, I'm already using a custom tag to handle 'page not found' requests, so if I could somehow capture the requested page, match it against a list of 'known-to-be-missing' pages, then I could code a way to forward to the 'new' destination." Sounds simple enough, eh?

For those of us using a shared-host provider such as CrystalTech or HostMySite, they're kind enough to allow us to create custom pages to handle certain HTTP errors, such as 404. It's usually found in the service provider's "control panel" under something like "IIS > Custom Error Pages." Once there, you usually have three options to pick from: 1) Default, 2) File and 3) URL. In most cases, "Default" loads the standard error page provided by our friends at Microsoft. "File" is just that, a flat, static, HTML page. What we want to use is "URL," so that we can use ColdFusion to help us out. In fact, I'll be nice and even provide a link to both CrystalTech's process and HostMySite's process. But before you do this, you'll need to at least set up a .CFM file somewhere on your site so you know what to enter into the URL path, right? So for now, let's assume you've created a file call "404.cfm" and placed in a directory structure like so: "/extensions/customtags/404.cfm"

So, assuming you've got your custom error page setup properly, you will now be able to capture a query string which contains the "requested URL" that really didn't exist. The easiest way to test this would be to enter this code onto your 404.cfm file, upload it to your site, then try a non-existent directory such as www.yourdomain.com/abcd/.


<cfset request.queryString = getPageContext().getRequest().getQueryString() />
<cfoutput>#request.queryString#</cfoutput>
<cfabort />

You should see something like this: "404;http://www.yourdomain.com:80/abcd/"

There's some great information coming through here. First, you'll notice that you're receiving the error number (404). Next, you'll see your domain also includes the port number being used. For example, if using HTTP, then you will most likely see the number 80, or if your using HTTPS, then you should probably see 443.

For this next part, you might have to adjust this if you ever use a colon ( : ) in your directory or page naming conventions (this is not generally used, so I wouldn't expect this to be much of an issue).

Look again at the query string that we've been given, what we really want to grab is everything after the port number. Or, the absolute path to the page or directory being requested. So this is what I came up with:


<!--- perform some manipulations to the 'requested url' to get at the actual request --->
<cfif isDefined("request.queryString")>
    <cfset requestedPage = listlast(request.queryString, ":") />
</cfif>
<cfif len(trim(requestedPage))>
    <!--- after removing everything before the port, we now need to remove the port number --->
    <cfset requestedPage = listdeleteat(requestedPage, "1", "/") />
    <!--- quick fix to create an absolute path from the site root to the requested page --->
    <cfset requestedPage = "/" & requestedPage />
</cfif>
<cfoutput>#requestedPage#</cfoutput>
<cfabort />

So, now if we use the same url we tried earlier, I should see something like: "/abcd/" Now, I've got a variable that I can use to match against to see if this is a "known" directory or page from our old site. Now we just need something to handle the "matching" and then receive a response to make decisions against.

Luckily, I've created a rather simple .CFC which can easily be modified to accommodate any "known" directories and/or pages, including .ASP, .PHP, etc.


<!------------------------------------------------------------------------------------------------------------

    Document:        /extensions/components/redirect.cfc
    Author:            Steve Withington
    Creation Date:    12/30/2008
    Copyright:        (c) 2008 Stephen J. Withington, Jr. | www.stephenwithington.com
    
    Purpose:        Handles redirects of old pages to new ones.

    METHODS/VAR:    1) getLocation() / newLocation
    
    Revision Log:    
    MM/DD/YYYY - sjw - comments.

------------------------------------------------------------------------------------------------------------->

<cfcomponent displayname="Handles redirects" hint="Pass me an old location, I'll give you the new location." output="no">

    <!---    1) getLocation()    --->
    <cffunction name="getLocation"
                    displayname="Get a new location for old links."
                    access="public"
                    returntype="string"
                    output="no">

    
        <cfargument name="oldLocation" required="false" default="" />
    
        <cfset var newLocation = "" />
    
        <cfswitch expression="#arguments.oldLocation#">

            <cfcase value="/index.html">
                <cfset newLocation = "/index.cfm" />
            </cfcase>

            <cfcase value="/about/news/default.php,/about/news/,/about/news">
                <cfset newLocation = "/news/index.cfm" />
            </cfcase>

            <cfcase value="/contact-us.asp">
                <cfset newLocation = "/contact/index.cfm" />
            </cfcase>

            <cfdefaultcase>
                <cfset newLocation = "" />
            </cfdefaultcase>

        </cfswitch>
    
        <cfreturn newLocation />
    
    </cffunction>

</cfcomponent>

Now, we just need to invoke the ColdFusion Component to see if there's a match.


<!--- check to see if the page requested matches any 'known' pages from the old site --->
<cftry>

    <cfinvoke component="extensions.components.redirect" method="getLocation" returnvariable="newLocation">

        <cfif isDefined("requestedPage") and len(trim(requestedPage))>
            <cfinvokeargument name="oldLocation" value="#requestedPage#" />
        </cfif>

    </cfinvoke>

    <cfif isDefined("newLocation") and len(trim(newLocation))>
        <cfset newPage = newLocation />
    </cfif>

    <cfcatch>
        <cfset newPage = "" />
    </cfcatch>

</cftry>

As you can see, if no match has been found, a variable called "newPage" is merely left blank. So, now we can write a little more code to accommodate both "known-to-be-missing" and "truly-unknown-and-really-missing" directories and pages. If a page is "known-to-be-missing", I can pass a search engine friendly header so that everything runs as smoothly as possible.

Here's the final document, aside from the .CFC above which should be kept separate.


<cfsilent>
<!------------------------------------------------------------------------------------------------------------

    Document:        /extensions/customtags/404.cfm
    Author:            Steve Withington
    Creation Date:    12/30/2008
    Copyright:        (c) 2008 Stephen J. Withington, Jr. | www.stephenwithington.com
    
    Purpose:        Handles requests for missing pages (HTTP 404).

    Notes:            Test this set up before using in a live environment. The 404 custom error page needs to be
                    set up in IIS (or via control panel in a third-party hosted environment).
    
    Revision Log:    
    MM/DD/YYYY - sjw - comments.

------------------------------------------------------------------------------------------------------------->

<!--- scope local variables --->
<cfparam name="requestedPage" default="" />
<cfparam name="newPage" default="" />
<!--- use a little of the underlying java to grab the queryString --->
<cfset request.queryString = getPageContext().getRequest().getQueryString() />
<!--- perform some manipulations to the 'requested url' to get at the actual request --->
<cfif isDefined("request.querystring")>
    <cfset requestedPage = listlast(request.queryString, ":") />
</cfif>
<cfif len(trim(requestedPage))>
    <!--- after removing everything before the port, we now need to remove the port number --->
    <cfset requestedPage = listdeleteat(requestedPage, "1", "/") />
    <!--- quick fix to create an absolute path from the site root to the requested page --->
    <cfset requestedPage = "/" & requestedPage />
</cfif>
<!--- check to see if the page requested matches any 'known' pages from the old site --->
<cftry>
    <cfinvoke component="extensions.components.redirect" method="getLocation" returnvariable="newLocation">
    <cfif isDefined("requestedPage") and len(trim(requestedPage))>
        <cfinvokeargument name="oldLocation" value="#requestedPage#" />
    </cfif>
    </cfinvoke>
    <cfif isDefined("newLocation") and len(trim(newLocation))>
        <cfset newPage = newLocation />
    </cfif>
    <cfcatch>
        <cfset newPage = "" />
    </cfcatch>
</cftry>
</cfsilent>
<cfif isDefined("newPage") and len(trim(newPage))>
<!--- requested page is a known 'old page' from prior site --->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<cfheader statuscode="301" statustext="Moved permanently" />
<cfheader name="Location" value="http://www.yourDomainHere.com#newPage#" />
<title>This page has moved to http://www.yourDomainHere.com<cfoutput>#newPage#</cfoutput></title>
</head>
<body>
This page has moved to <cfoutput><a href="http://www.yourDomainHere.com#newPage#">http://www.yourDomainHere.com#newPage#</a></cfoutput>
</body>
</html>
<cfelse>
<!--- requested page is NOT a known 'old page' from prior site and doesn't exist --->
<cf_layout     title="Hmm, the page you're looking for can't be found."
                keywords="404,page,not,found"
                description="Hmm, the page you're looking for can't be found. You may have clicked a bad link or mistyped the web address.">

    <h1>Hmm, the page you're looking for can't be found.</h1>
    <p>You may have clicked a bad link or mistyped the web address.</p>
    <ul>
        <li><a href="/">Return home</a></li>
        <li><a href="javascript:history.back();">Go back to the previous page</a></li>
    </ul>
</cf_layout>
</cfif>

As you can see, I like to use a custom tag to handle the layout of my pages, etc. You can find out more about that at Raymond Camden's site.

I hope this helps a fellow ColdFusion developer. Thanks for reading!

I've Decided To (try to) Learn Java

Head First Java

As the new year approaches, I'm adding "Learn Java" to my personal list of things to do in 2009. I've been wanting to pick up some Java skills for awhile now and never really set it as a priority. Don't worry, I have no plans to abandon ColdFusion. Quite the contrary really.

In my school days, I was required to learn a foreign language. Victims of "location" and "school budgets," each grade school within my childhood hometown of Akron, Ohio offered one foreign language option and mine happened to be Spanish. (Friends at other schools were able to learn French, or even German.) Eventually, in high school, Latin was also offered as a foreign language option. To my excitement, I took both Latin and Spanish. In the end, I truly believe Latin helped me in not only my Spanish, but also my English! (Which some of my readers might take argument with, to be sure.) Anyway, as it turned out, Latin was/is the basis of approximately 60% of the English language. In addition, Spanish, French, and many other languages are also based on Latin in some form or another, so it's no wonder that picking up Latin skills could in turn help one in other languages as well.

As most users of ColdFusion know, Java (or J2EE) is the underlying engine that drives ColdFusion. So in much the same way that I felt Latin helped me in my English and Spanish, I'm hoping Java will also help me in not only my ColdFusion programming, but in other areas as well (object oriented code, etc.).

I understand that learning a language is an ongoing process and never really "ends." Heck, I'm still learning ColdFusion even though I've been using it since CF5. I also understand that I'll probably never really achieve "greatness" in Java considering the fact that I personally know of people that have spent their full four years in college learning this extremely complex language.

After asking and searching around for a resource to help me in my quest for Java knowledge, I've decided on the book "Head First Java, 2nd Edition" by Kathy Sierra and Bert Bates published by O'Reilly. My book arrived just in time for Christmas and after reading the introduction and flipping around, I can say that I'm truly excited to dive right in. I'm just hoping I'll be able to swim the Java waters.

Extending ColdFusion's List Functions: Append or Prepend Individual List Items

Recently, I ran into a situation where I was typing out a bunch of cfinvokeargument tags for a long list of variables and when I began typing essentially the same information over and over again I thought "I could probably do this more efficiently!" So, I threw together a fairly simple user defined function (UDF) that I wrapped up into a ColdFusion component (.cfc).

The theory is fairly simple. Take a list, loop over each list item (or element) and prepend each individual list item with a predefined value.

For example, if a list contains the following values: (ItemName,ItemNumber,Quantity,PaymentDate). You could prepend each list item with "request." thus receiving a new list containing: (request.ItemName,request.ItemNumber,request.Quantity,request.PaymentDate).

This varies from ColdFusion's built in functions ListAppend and ListPrepend in that the built in functions add list items (or elements) to a list, but do not actually modify the list items themselves. Whereas I wanted to modify each individual list item or element, not necessarily add new list items at the beginning or end of the list.

While I was at it, I went ahead and threw in a method to append list items/elements as well. Hope this saves time for someone else too.

Here's the ColdFusion component:


<!---------------------------------------------------------------------------------------------------------------

    Document:        /extensions/components/listFunctionExtensions.cfc
    Author:            Steve Withington (http://www.stephenwithington.com)
    Creation Date:    12/22/2008
    Copyright:        (c) 2008 Stephen J. Withington, Jr. | stephenwithington.com

    License:        This code may be used freely.
                    You may modify this code as you see fit, however, this header must remain intact.
                    
                    This code is provided as is. I make no warranty or guarantee.
                    Use of this code is at your own risk.
    
    Purpose:        Prepend (or append) a value to the beginning (or end) of each item in a list.
    
                    For example, if a list contains the following values:
                    (ItemName,ItemNumber,Quantity,PaymentDate)
                    you could prepend each list item with "request." thus receiving a new list containing
                    (request.ItemName,request.ItemNumber,request.Quantity,request.PaymentDate).
                    This could easily be modified to allow for custom delimiters, etc. but
                    I wanted to keep this simple.

    Example Usage:
    http://www.stephenwithington.com/blog/index.cfm/2008/12/22/Extending-ColdFusions-List-Functions-Append-or-Prepend-Individual-List-Items
    
    Revision Log:    
    MM/DD/2008 - sjw - notes.

---------------------------------------------------------------------------------------------------------------->

<cfcomponent     displayname="List Function Extensions"
                output="false"
                hint="PrependListItems() and AppendListItems() methods.">


    <!--- prependListItems(currentList, prependValue) --->
    <cffunction name="prependListItems"
                access="public"
                returntype="string"
                output="false">


        <cfargument name="currentList"
                    type="string"
                    required="yes" />


        <cfargument name="prependValue"
                    type="string"
                    required="yes" />


        <cfset var listResult = "" />
        <cfset var listToPrepend = arguments.currentList />
        <cfset var theValue = arguments.prependValue />
        <cfset var tempArray = arrayNew(1) />

        <cfloop list="#listToPrepend#" index="i">
            <cfset temp = arrayAppend(tempArray, theValue & i) />
        </cfloop>

        <cfset listResult = arrayToList(tempArray, ",") />

        <cfreturn listResult />

    </cffunction>


    <!--- appendListItems(currentList, appendValue) --->
    <cffunction name="appendListItems"
                access="public"
                returntype="string"
                output="false">


        <cfargument name="currentList"
                    type="string"
                    required="yes" />


        <cfargument name="appendValue"
                    type="string"
                    required="yes" />


        <cfset var listResult = "" />
        <cfset var listToAppend = arguments.currentList />
        <cfset var theValue = arguments.appendValue />
        <cfset var tempArray = arrayNew(1)>

        <cfloop list="#listToAppend#" index="i">
            <cfset temp = arrayAppend(tempArray, i & theValue) />
        </cfloop>

        <cfset listResult = arrayToList(tempArray, ",") />

        <cfreturn listResult />

    </cffunction>

</cfcomponent>

Here's an example of both the PrependListItems method and AppendListItems method:


<cfset tempList = "ItemName,ItemNumber,Quantity,PaymentDate" />
                    
<cfscript>
    args = structNew();
    args.currentList = tempList;
    args.prependValue = "request.";
</cfscript>

<!--- you may need to modify this to your placement of listFunctionExtensions.cfc --->
<cfinvoke     component="extensions.components.listFunctionExtensions"
            method="prependListItems"
            argumentcollection="#args#"
            returnvariable="myNewPrependedList" />


<ul>
    <cfloop list="#myNewPrependedList#" index="i">
        <cfoutput><li>#i# – #listlast(i, '.')#</li></cfoutput>
    </cfloop>
</ul>

<hr size="1" />

<cfscript>
    args = structNew();
    args.currentList = tempList;
    args.appendValue = "1";
</cfscript>

<cfinvoke     component="extensions.components.listFunctionExtensions"
            method="appendListItems"
            argumentcollection="#args#"
            returnvariable="myNewAppendedList" />


<ul>
    <cfloop list="#myNewAppendedList#" index="i">
        <cfoutput><li>#i#</li></cfoutput>
    </cfloop>
</ul>

More Entries

© 2026, Stephen J. Withington, Jr.  |  Hosted by Hostek.com

Creative Commons License   |   This work is licensed under a Creative Commons Attribution 3.0 Unported License.