How to create a 301 redirect with ASP?

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 ASP, 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 Microsoft ASP language. In fact, the main steps of this process only consist of a two 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 ASP 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 an ASP file in order to be able to execute ASP code on your server. Then, copy the following code, as the very first lines of your ASP file, and replacing the by the real destination address of your 301.

Response.Status="301 Moved Permanently"

In the ASP language, Response object 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 Response object 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 ASP redirection, you are free to use any command you need before the response object 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 an ASP variable is then easy, and reusing it in the Response object is a matter of a single line modification: