How to Redirect a Web Page

Avatar of Robin Rendle
Robin Rendle on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

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 are redirected 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.

HTTP response codes

Every time we enter a URL or make a request from a browser we’re using the Hypertext Transfer Protocol (HTTP). Although this sounds like a really cool name for a sci-fi cop movie it’s actually the process by which we request assets such as CSS, HTML and images from a server. After we’ve sent a request these assets will then give a response like “hey I’m here, let’s go!” (response code HTTP 200 OK). There are many different kinds of HTTP response code, the most familiar perhaps being 404 Not Found; web pages can respond with a 404 status but so can any other asset that we request, whether that’s an image or any other kind of asset.

Every HTTP response is categorized under a certain three digit number, so 404 Not Found is a 4XX status code to clarify that it’s a client error and 200 is in the 2XX category to signify that it’s a success message of some kind. We’re interested in the 3XX category of HTTP response, like 301 Moved Permanently or 302 Found, because these are the status codes specifically set aside for redirects. Depending on the method we choose we won’t necessarily need to know about these codes but it’s essential for others.

In our case we’ll use a 301 redirect because some web browsers or proxy servers will cache this type, making the old page inaccessible which, in this instance, is exactly what we want.

So how do we actually go about redirecting a web page?

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.html file 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.

Ruby on Rails redirects

From any controller in a Rails project, we can quickly redirect to a new website with redirect_to and the :status option set to :moved_permanently. That way we override the default 302 status code and replace it with Moved Permanently:

class WelcomeController < ApplicationController
  def index
    redirect_to 'http://new-website.com', :status => :moved_permanently 
  end
end

In Rails 4 there’s any easier way to handle these requests where we can add a redirect in the routes.rb file which automagically sends a 301 response:

get "/blog" => redirect("http://new-website.com")

Or if we want to redirect every article on the blog to posts on the new website we can do so by replacing the above with the following:

get "/blog/:post" => redirect("http://new-website.com/blog/%{post}")

.NET redirects

I’ve never written anything with the .NET framework before but it looks like there’s clear documentation over on Microsoft’s Developer Network.

Node.js redirects

Here’s a very quick local setup that explains how redirects work with Node. First we include the http module and create a new server, followed by the .writeHead() method:

var http = require("http");

http.createServer(function(req, res) {
  res.writeHead(301,{Location: 'http://new-website.com'});
  res.end();
}).listen(8888);

If you make a new file called index.js and paste the code above and then run node index.js in the command line you’ll find the local version of the website redirecting to new-website.com. But to redirect all the posts in the /blog section we’ll need to parse the URL from the request with Node’s handy url module:

var http = require("http");
var url = require("url");

http.createServer(function(req, res) {
  var pathname = url.parse(req.url).pathname;
  res.writeHead(301,{Location: 'http://new-website.com/' + pathname});
  res.end();
}).listen(8888);

Using the .writeHead() function we can then attach the pathname from the request to the end of URL string. Now it’ll redirect to the same path on our new site. Yay for JavaScript!

Flask redirects

With the Flask framework on top of Python we can simply create a route that points to subpages with the redirect function, again 301 has to be an option that is passed in at the end because the default is set to 302:

@app.route('/notes/<page>')
def thing(page):
  return redirect("http://www.new-website.com/blog/" + page, code=301)

If you know of any other tricks to redirect a web page add a comment below and I’ll update this post with the latest info.