How to create a 301 redirect with ColdFusion?

Creating a 301 redirect as part of the server configuration is always the best solution. But if you only need to build a local redirection, only from one specific file of your server, it can be useful to make it in a scripting language such as Adobe ColdFusion, rather than configuring the whole server for an exceptional behaviour.

This page describes the few steps you'll need to follow in order to set up a 301 redirect using Adobe ColdFusion language. In fact, the main steps of this process only consist of a few lines code you'll have to paste on top of the file you need to redirect. That's all.



Defining the 301 code and the target address.
As Adobe ColdFusion is a server side language, it can easily compute some data even before any answer has been sent to the client browser from the server. Using this behaviour, and some adequate commands, it's then easy to dynamically write a new header for a request and define it as a 301.

To achieve this, first open the file from which you want to set up the redirection. This file must, of course, be a CFM file in order to be able to execute ColdFusion code on your server. Then, copy the following code, as the very first lines of your Adobe ColdFusion file, and replacing the http://www.newlocation.com by the real destination address of your 301.

<cfheader statuscode="301" statustext="Moved permanently">
<cfheader name="Location" value="http://www.newlocation.com">

In the ColdFusion language, cfheader tag is used to define the answer of the server to a specific request, and so can be used to define a 301 redirect. This way, the first information your client will receive is the relocation command. Obeying to the redirection code, it will not keep in consideration any line of the following page.



Dynamically defining the redirection target.
If the cfheader tag must be the first instruction to be sent to the client, it's not necessarly the first one to be executed by the server. Using ColdFusion redirection, you are free to use any command you need before the cfheader tag definition, as long as you don't send any data to the client browser.


You can then easily imagine that the target address of the redirection is defined following attributes present in the original page address, session's values or any database entry. Storing this new address in a ColdFusion variable is then easy, and reusing it in the cfheader Location tag is a matter of a single line modification.