FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home » Htaccess » 301 Redirect Cheatsheet

301 Redirect Cheatsheet

301 Redirect Cheatsheet Ultimate Redirect Cheatsheet for multiple programming languages. Redirecting Users with Javascript redirect, meta refresh redirect, and php redirect, also htaccess methods, python, coldfusion, asp, perl, etc.

301 Redirect Cheatsheet

November 29th, 2007

Contents

  1. Redirection Methods
  2. Redirect with meta http-equiv tags
    1. Refresh meta http-equiv tag
  3. Redirect with javascript
    1. Basic javascript Redirect method
    2. Redirect after specific time period
  4. Redirect with PHP
    1. Using "Location" header
    2. Using "Refresh" header
    3. Ultimate PHP method
  5. Redirect with Perl
    1. Simple 302 Redirect with perl
    2. Simpler 302 Redirect with perl
  6. Redirect with ColdFusion (CFM)
    1. Using cheader for 301 "permanent" redirect
    2. Using clflocation for 302 "temporary" redirect
  7. Redirect with ASP (VB Script)
    1. 301 Redirect
  8. Redirect with shell script
    1. 302 Redirect with sh shell script
  9. Redirect with mod_rewrite in apache htaccess
    1. 301 Redirect
    2. 302 Redirect
  10. Redirect with mod_alias in apache htaccess
    1. 301 Redirect
      1. or with RedirectPerm
      2. or with RedirectMatch
    2. 302 Redirect
      1. or with RedirectTemp
      2. or with RedirectMatch
    3. Redirect with ErrorDocument in apache htaccess
      1. 302 Redirect
    4. Redirect with Python / Django

I got tired of always having to search google to remember the syntax for issuing seo friendly (300, 301, 302, 303, 305, 306, 307) Redirects using multiple programming languages and methods... so I made my own list!

Redirection Methods

Am I missing something? Most definately! Please use the comment form below to suggest new code.

Redirect with meta http-equiv tags

These go in the <head> </head> section of your html. Usually when you use this meta redirect method you should also use the javascript method, just to be safe.

Refresh meta http-equiv tag

Redirects to http://www.askapache.com after 0 seconds.

<meta http-equiv="refresh" content="0;url=http://www.askapache.com" />

Redirect with javascript

These go in the <head> </head> section of your html.

Basic javascript Redirect method

Will redirect user to http://www.askapache.com immediately

<script type="text/javascript">
window.location.href='http://www.askapache.com';
</script>

Redirect after specific time period

This will redirect to http://www.askapache.com after 2 seconds

<body onload="javascript:setTimeout(function(){window.location.href='http://www.askapache.com'},2000);">

Redirect with PHP

Using "Location" header

<?php
header('Location:http://www.askapache.com');
exit;
exit();
?>

Using "Refresh" header

<?php
header('Refresh: 0; URL=http://www.askapache.com');
exit;
exit();
?>

Ultimate PHP method

It redirects to a page specified by "$url". $mode can be:

  • LOCATION: Redirect via Header "Location"
  • REFRESH: Redirect via Header "Refresh"
  • META: Redirect via HTML META tag
  • JS: Redirect via JavaScript command
<?php
function do_redirect($url,$mode)
{
    if (strncmp('http:',$url,5) && strncmp('https:',$url,6)) {
        $starturl = ($_SERVER["HTTPS"] == 'on' ? 'https' : 'http') . '://'.
        (empty($_SERVER['HTTP_HOST'])? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST']);
        if ($url[0] != '/') $starturl .= dirname($_SERVER['PHP_SELF']).'/';
        $url = "$starturl$url";
    }
    switch($mode) {
        case 'LOCATION':
        header("Location: $url");
        exit;
        case 'REFRESH':
        header("Refresh: 0; URL=\"$url\"");
        exit;
        case 'META':
        exit;
        default:
        ?><script type="text/javascript">
        window.location.href='<?=$url?>';
        </script><?
    }
    exit;
}
?>

Redirect with Perl

Simple 302 Redirect with perl

#!/usr/bin/perl
my $URL = "http://www.askapache.com";
print "Status: 302 Moved\nLocation: $URL\n\n";

Simpler 302 Redirect with perl

#!/usr/bin/perl
print "Location: http://www.askapache.com\n\n";
exit;

Redirect with ColdFusion (CFM)

Using cheader for 301 "permanent" redirect

<cfheader statuscode="301" statustext="Moved Permanently">
<cfheader name="Location" value="http://www.askapache.com">
<cfabort>

Using clflocation for 302 "temporary" redirect

<cflocation url="http://www.askapache.com">

Redirect with ASP (VB Script)

301 Redirect

<%@ Language=VBScript %>
<%
response.status="301 moved permanently"
Response.AddHeader "Location", "http://www.askapache.com"
%>

Redirect with shell script

302 Redirect with sh shell script

#!/bin/sh
echo "Content-type: text/html"
echo "Location: http://www.askapache.com";
echo "";
exit 0;

Redirect with mod_rewrite in apache htaccess

See also Ultimate Apache htaccess article and URL Redirection

301 Redirect

Redirects permanently when a request is made to site.com/thisword.html to http://www.askapache.com

RewriteEngine On
RewriteBase /
RewriteRule ^thisword\.html$ http://www.askapache.com [R=301,NC,L]

302 Redirect

Redirects temporarily when a request is made to site.com/thisword.html to http://www.askapache.com

RewriteEngine On
RewriteBase /
RewriteRule ^thisword\.html$ http://www.askapache.com [R,NC,L]

Redirect with mod_alias in apache htaccess

301 Redirect

Redirect 301 /thisword.html http://www.askapache.com

or with RedirectPerm

RedirectPerm /thisword.html http://www.askapache.com

or with RedirectMatch

RedirectMatch 301 ^thisword\.html$ http://www.askapache.com

302 Redirect

Redirect 302 /thisword.html http://www.askapache.com

or with RedirectTemp

RedirectTemp /thisword.html http://www.askapache.com

or with RedirectMatch

RedirectMatch 302 ^thisword\.html$ http://www.askapache.com

Redirect with ErrorDocument in apache htaccess

302 Redirect

Issues a 302 Redirect to http://www.askapache.com when a file is not found. See also Force Apache to output any HTTP Status Code with ErrorDocument

ErrorDocument 404 http://www.askapache.com

Redirect with Python / Django

Thanks to thebjorn for contributing this first one, which issues a 302 Redirect.

from django import http
def view(request):
return http.HttpResponseRedirect('http://www.askapache.com/')

This example was contributed by John and shows how to issue a proper 301 Redirect, additional info on this below the example.

from django import http
def view(request):
return http.HttpResponsePermanentRedirect ('http://www.askapache.com/')

Django includes a number of HttpResponse subclasses that handle different types of HTTP responses. Like HttpResponse, these subclasses live in django.http.

HttpResponseRedirect
The constructor takes a single argument -- the path to redirect to. This can be a fully qualified URL (e.g. 'http://www.askapache.com/htaccess/') or an absolute URL with no domain (e.g. '/htaccess/'). Note that this returns an HTTP status code 302.
HttpResponsePermanentRedirect
Like HttpResponseRedirect, but it returns a permanent redirect (HTTP status code 301) instead of a "found" redirect (status code 302).
HttpResponseNotModified
The constructor doesn't take any arguments. Use this to designate that a page hasn't been modified since the user's last request (status code 304).

http://www.askapache.com/htaccess/list-of-methods-to-redirect-users-to-different-page.html#comments

Reader Comments

  1. Abraham NooB ~October 30, 2011 @ 9:59 pm
    Hi, If I want to redirect all pages from my old website to the home page of my new website, would this be enough:
    RedirectMatch 301 (.*) http://www.newdomain.com/
  2. Pingback:TRICKS FORUM » Beginner’s Guide to SEO: Best Practices – Part 2/3

  3. Big B. ~July 9, 2010 @ 5:53 am
    Script "Ultimate PHP method" reported Parse error: syntax error, unexpected $end
  4. Stefanos ~June 24, 2010 @ 6:44 am
    Great post! I found it really useful. Any idea if the header redirect is seo fiendly. Aa far as I know the best one is the .htaccess one. Any advice on this issue.
  5. OneDame ~June 15, 2010 @ 9:23 am
    Hey, thanks for this list. It really helped me out!
  6. John ~May 8, 2010 @ 5:27 am

    Heya - the Python example actually would prompt a 302 redirect

    In order to prompt a 301, note that you would need to utilize the HttpResponsePermanentRedirect class a la:

    from django import http
    def view(request):
    return http.HttpResponsePermanentRedirect (&#039;http://www.askapache.com&#039;)

    Reference: httpresponse-subclasses

  7. AskApache ~March 26, 2010 @ 2:23 am
    @Luis Apache loads every time anyway@... so using it
  8. Mara Alexander ~March 3, 2010 @ 7:31 pm
    The links under the "Redirect Method" section appear to have been meant to be anchor links, yet they all redirect to your main page (askapache.com). I'm thinking the anchor tags on the page weren't done correctly.
  9. Luis ~August 17, 2009 @ 4:14 pm
    Which would be the preferred redirect method: PHP or Mod Rewrite ? Why? I'm just curious abut it.
  10. Natasha ~March 27, 2009 @ 1:04 pm
    This is great information. Thanks a bunch
  11. David Simmons ~June 27, 2008 @ 1:11 pm
    Excellent collection! Thx
  12. nBridges Media ~December 10, 2007 @ 1:16 am
    Thanks for such nice list
  13. thebjorn ~November 30, 2007 @ 2:54 pm
    Thanks for the list! saved me a bunch of time. If you'd like to add the code for Django/Python it is: from django import http def view(request): return http.HttpResponseRedirect('http://www.htaccesselite.com')
  14. AskApache ~October 24, 2007 @ 4:19 am

    @ Ash

    Thanks! I will have to go through and clean up the code, especially adding code to do 307 Temporary Redirects, which should almost always be used instead of a 302 Redirect.

  15. Ash Nallawalla ~October 8, 2007 @ 8:46 am
    Thanks for this fantastic checklist! I will send my students to this page.

Add Comment!

Leave a Reply

Your email address will not be published.


Google +

It's very simple - you read the protocol and write the code. -Bill Joy

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

Site Map | Contact Webmaster | Glossary | License and Disclaimer | Terms of Service |

↑ TOPMain