Redirection

Learn how to perform temporary redirection and permanent redirection using PHP, htaccess with mod_rewrite, and Javascript.

There is many ways to redirect traffic. A couple of examples:

  • Server side scripting such as PHP, ASP.NET and Ruby.
  • Htaccess using the mod_rewrite or mod_alias module in Apache webserver.
  • Javascript.

I will explain how to perform temporary redirection and permanent redirections using the above methods.

Redirection using PHP

In PHP you can redirect using the header() function. To send a temporary 302 redirection from PHP:

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

It is important that the script has not printed any HTML before you make the redirection, or you will get a warning about:

Cannot modify header information - headers already sent by ...

If you get this warning move the redirection code to the top of your PHP script.

To make a permanent 301 redirection using PHP:

<?php
header('Location: http://www.example.com/', true, 301);
exit;
?>

Redirection with htaccess

With the Apache webserver you can use a file called “.htaccess” to perform redirections. In the htaccess file you can use so-called directives or commands. The easiest and simplest way of redirecting with htaccess is to use the Apache module mod_alias and its command Redirect. Here’s is how to make a temporary 302 redirection with htaccess:

Redirect /articles.html http://www.example.com/new-articles.html

If you copy the above to a htaccess file on your domain “example.com”, it will redirect http://www.example.com/articles.html to http://www.example.com/new-articles.html. To make a permanent 301 redirection use:

Redirect 301 /articles.html http://www.example.com/new-articles.html

The module mod_rewrite is the most powerful and allows you can make very complicated redirections and changes to the requested URL, so-called rewrites. Mod_rewrite can be used to ie redirect from an old domain to a new or to redirect non-www traffic to www. Its also possible to hotlink protect images or redirect based on language with mod_rewrite. Because mod_rewrite is so complex I have written an article on how to redirect with htaccess and mod_rewrite.

Redirection with Javascript

You can also use Javascript to perform redirections. It works by placing some Javascript code on your HTML pages. The following code will make your page redirect to example.com:

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

Place the code between your head-tags (<head></head>). You can also redirect using relative URLs:

<script type="text/javascript">
window.location = "../some-dir/index.html";
</script>

Using the above code the user will be able to go back to the original page by using the “Back” button in the browser. This is often undesirable, so instead you should use:

<script type="text/javascript">
window.location.replace("../some-dir/index.html");
</script>