Web-redirects

How to Redirect a Web Page

A redirect is when a web page is visited at a certain URL, it changes to a different URL. For instance, a person visits “website.com/page-a” in their browser and they areredirected to “website.com/page-b” instead. This is very useful if we want to redirect a certain page to a new location, change the URL structure of a site, remove the “www.” portion of the URL, or even redirect users to another website entirely (just to name a few).

Let’s say we’ve just moved our website and we want to shut down the old one. However we don’t want all those pages from the old site to give a dreaded 404 Not Found. What we need is for those old links to redirect to the same content on our new site.

Here’s our example: we want old-website.com/blog/post to redirect to new-website.com/blog/post, along with all the other posts that use that same URL format. Also it would be nice if our redirects would report to search engines that this change is permanent so they should update accordingly.

So how do we that? Well, before we start we need to learn a little about HTTP.

HTML redirects

Perhaps the simplest way to redirect to another URL is with the Meta Refresh tag. We can place this meta tag inside the <head> at the top of any HTML page like this:

<meta http-equiv="refresh" content="0; URL='http://new-website.com'" />

The content attribute is the delay before the browser redirects to the new page, so here we’ve set it to 0 seconds. Notice that we don’t need to set a HTTP status code, but it’s important to double check the weird opening and closing of the quotes above (there are quotes within quotes, so they need to be different types and matching).

Although this method is the easiest way to redirect to a web page there are a few disadvantages. According to the W3C there are some browsers that freak out with the Meta refresh tag. Users might see a flash as page A is loaded before being redirected to page B. It also disables the back button on older browsers. It’s not an ideal solution, and it’s discouraged to use at all.

A safer option might be to redirect the website with JavaScript.

JavaScript redirects

Redirecting to another URL with JavaScript is pretty easy, we simply have to change the location property on the window object:

window.location = "http://new-website.com";

JavaScript is weird though, there are LOTS of ways to do this.

window.location = "http://new-website.com";window.location.href = "http://new-website.com";window.location.assign("http://new-website.com");window.location.replace("http://new-website.com");

Not to mention you could just use location since the window object is implied. Or self or top.

With the location object we can do a lot of other neat stuff too like reload the page or change the path and origin of the URL.

There are a few problems here:

  1. JavaScript needs to be enabled and downloaded/executed for this to work at all.
  2. It’s not clear how search engines react to this.
  3. There are no status codes involved, so you can’t rely information about the redirect.

What we need is a server side solution to help us out by sending 301 responses to search engines and browsers.

Apache redirects

Perhaps the most common method of redirecting a web page is through adding specific rules to a `.htaccess` on an Apache web server. We can then let the server deal with everything.

`.htaccess` is a document that gives us the ability to give orders to Apache, that bit of software that runs on the server. To redirect users to our new site we’ll make a new .htaccess file (or edit the existing one) and add it to the root directory of the old website. Here’s the rule we’ll add:

Redirect 301 / http://www.new-website.com

Any page that the user visits on the old website will now be redirected to the new one. As you can see, we put the HTTP response code right at the front of the redirect rule.

It’s worth mentioning that this kind of redirect only works on Linux servers with the mod_rewrite enabled, an Apache module which lets us redirect requested URLs on the server by checking a certain pattern and, if that pattern is found, it will modify the request in some way. Most hosting companies have this enabled by default, but contacting them is your best bet if there’s a problem. If you’re looking for more info on mod_rewrite then there’s a great tutorial on tuts+. There are also lots of .htaccess snippets here on CSS-Tricks.

Back to our example, if we use the code above then a user will go to “old-website.com/blog/post” and be sent to “new-website.com” which isn’t very user friendly because they won’t see actual page they asked for. Instead, we’ll add the following rule to our `.htaccess` file in order to redirect all those blog posts to the right place:

RedirectMatch 301 /blog(.*) http://www.new-website.com$1

Or perhaps we want to redirect individual pages very specifically. We can add the rules like this:

Redirect 301 /page.html http://www.old-website/new-page.html

And for errors we can redirect users to our 404 page (probably chock full of puns and gifs):

<IfModule mod_rewrite.c>  RewriteEngine on  RewriteCond %{REQUEST_FILENAME} !-f  RewriteCond %{REQUEST_FILENAME} !-d  RewriteRule .* 404.html [L]</IfModule>

First we check if we have the mod_rewrite module is available then we can turn it on and, if the file or directory is not found, we send the user off to our 404 page. It’s sort of neat that the contents of the page they see will be from the 404.htmlfile whilst the requested URL will remain the same.

If you’re not comfortable with messing around with `.htaccess` files and you have WordPress installed then there’s a nifty extension that can deal with this stuff for us.

Nginx redirects

If your server is running Nginx as the web server, then in the `nginx.conf` file you can add a server block to handle these redirect requests:

server {  listen 80;  server_name old-website.com;  return 301 $scheme://new-website.com$request_uri;}

Again we’re using the 301 HTTP response and, with the scheme variable, we’ll request http:// or https:// depending on what the original website used. It might be a good idea to take a closer look at the HTML5 Boilerplate nginx.conf for best practices on other Nginx related things.

Lighttpd redirects

For those servers running a Lighttpd web server, you make a redirect by first importing the mod_redirect module and using url.redirect:

server.modules  = (  "mod_redirect")$HTTP["host"] =~ "^(www\.)?old-website.com$" {  url.redirect = (    "^/(.*)$" => "http://www.new-website.com/$1",  )}

PHP redirects

With PHP we can use the header function, which is quite straightforward:

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

This has to be set before any markup or content of any other sort, however there is one small hitch. By default the function sends a 302 redirect response which tells everyone that the content has only been moved temporarily. Considering our specific use case we’ll need to permanently move the files over to our new website, so we’ll have to make a 301 redirect instead:

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

The optional true parameter above will replace a previously set header and the 301 at the end is what changes the response code to the right one.