Using cfheader when doing redirects

My office is undergoing a huge redesign, and all pages are being moved and/or having their extensions changed (from .htm to .cfm). Our webmaster has dictated that we need to do a redirect for every single page so that no one gets a 404 error.

We’re talking thousands upon thousands of pages, and after getting some good advice in the Server Management forum here on Sitepoint, I came up with a way to do the redirects sort of automatically.

Since we’ve been keeping an Excel spreadsheet of the old and new page locations, I decided to import that spreadsheet into our database, and use the database to handle the redirects.

Basically, I built a custom 404 page and had our server guy point the webserver to it. The page takes the old url and queries the database to find it. If it finds a match, it plugs the new url for that page into a meta refresh tag and displays a message that the page has been moved. If no match is found, it displays the standard 404 message.

Since I want search engines to know that the pages have been moved, I decided to stuff a cfheader tag into the mix, but I’m not certain I’m doing it right. This is what I have in the head section of the 404 page:

<cfquery name="redirect" datasource="#ourdsn#">
SELECT new_url
FROM redirects
WHERE old_url = <cfqueryparam value="#requeststring#" cfsqltype="cf_sql_varchar">
</cfquery>
<cfif #redirect.recordcount# neq 0>
<cfheader name="location" value="http://www.ourdomain.com#redirect.new_url#">
<cfheader statuscode="301" statustext="Moved Permanently" />
<meta http-equiv="refresh" content="5;url=<cfoutput>#redirect.new_url#</cfoutput>" />
<cfelse>
<cfheader statuscode="404" statustext="Not Found" />
</cfif>

Is this the proper way to do this sort of thing, or am I totally off-base?

Couple of thoughts. First, your webserver can redirect without you having to create a bunch of HTMs or using a custom 404. A really simple one would probably be just to redirect all .HTM to .CFM. If pagerank is important to you (if the site is external), this also helps the search engines know what the new location is for the old page.

If your webmaster is unwilling or unable to do this (or you have some web server that can’t do this for some reason), why not just have your 404 look to see if the page is HTM, and if it is, redirect to CFM? This saves yourself the call to the database. If the page is CFM, then just display the normal 404. This work work like follows:

  1. User goes to invalidpage.htm which 404s.

  2. 404 sees that user is trying to get to an HTM page and redirects to invalidpage.cfm

  3. Since invalidpage.cfm does not exist, but it is CFM instead of HTM, show normal 404 message.

  4. User goes to validpage.htm which 404s.

  5. 404 sees that user is trying to get to an HTM page and redirects to validpage.cfm

  6. Since validpage.cfm exists, user is shown page.