Website Redirects

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='https://google.com'" />

This also works for WordPress and Drupal 8.

The content attribute is the delay before the browser redirects to the new page, so here we’ve set it to 0 seconds.

JavaScript redirects

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

<script>
window.location = "http://google.com";
</script>

There are LOTS of ways to do this.

window.location = "http://google.com";
window.location.href = "http://google.com";
window.location.assign("http://google.com");
window.location.replace("http://google.com");

This also works for WordPress and Drupal 8.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *