Easy ways to create a 301 redirect in code

Since my post the other day on A simple way to correct the hostname for your website I’ve been thinking about ways to do the same in other languages so I thought I should share my findings with you. I’ll only cover the most common web languages and methods, but if you think I’ve missed any out then add them in the comment section below for the benefit of others.

Mod_Rewrite

The most common way to redirect a website is within apache itself. This can be done in the vhost or the .htaccess file with mod_rewrite.

RewriteEngine On
rewriteCond %{http_host} !www.example.com
rewriteRule ^(.*) http://www.example.com/$1 [R=301,L]

Ruby

Most places on the internet and in books will tell you to use:

require "socket"

if Socket.gethostname != "www.example.com" then
    headers["Status"] = "301 Moved Permanently"
    redirect_to "http://www.new-url.com" + request.request_uri
end

However I have discovered that the above actually sends a 302 header which is not great for search engines (Thanks to zacharypinter). Instead you should use the following.

require "socket"

if Socket.gethostname != "www.example.com" then
    head :moved_permanently, :location => "http://www.example.com" + request.request_uri
end

JSP and Java

if (request.getServerName() != "www.example.com") {
    response.setStatus(301);
    response.setHeader( "Location", "http://www.example.com" + request.getRequestURI());
    response.setHeader( "Connection", "close" );
}

ASP

if Request.ServerVariables() != "www.example.com" then
    Response.Status="301 Moved Permanently"
    Response.AddHeader "Location", "http://www.example.com/" & Request.ServerVariables("SCRIPT_NAME") & "?" & Request.ServerVariables("QUERY_STRING")
end if

PHP

This is a simplified version of the code I put in my last post, but it will work just as well.

if ($_SERVER['HTTP_HOST'] != 'www.example.com') {
    header ('HTTP/1.1 301 Moved Permanently');
    header ('Location: http://www.example.com' . $_SERVER['REQUEST_URI']);
    exit;
}

That is all I have time to write today, but I hope these are useful to you all.

Leave a Reply

Your email address will not be published. Required fields are marked *