A list of redirects  Print this Article

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 locationproperty 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_rewriteenabled, 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:// orhttps:// 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 themod_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_toand 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 theroutes.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

// 302 redirect (sometimes)
Response.Redirect("http://www.new-location.com");

// 301 redirect (yes please!)
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "http://www.new-location.com");

// or without the need for string
Response.Redirect("http://www.new-location.com", false);
Response.StatusCode = (int)System.Net.HttpStatusCode.MovedPermanently; 
Response.End();

// or with .NET 4.0
Response.RedirectPermanent("http://www.new-loca

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 thehttp 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)
 

Was this answer helpful?

Related Articles

What is an SSL certificate?
A SSL certificate is an electronic document signed by a certification authority. SSL is an...
What is validation process for issuing an SSL certificate?
The validation procedures are different and depend on the certificate validation type (DV, OV or...
What is SSL?
SSL (Secure Sockets Layer) is a standard security technology for establishing an encrypted link...
What does a warranty mean?
The warranty that you get when you purchase an SSL certificate insurers the end user up to a...
What is a Wildcard option?
Certificates with a Wildcard option, secure the main domain name (e.g. your-address.com) and...