Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

How to Redirect URLs

Want to redirect a URL from one location to another? This simple guide shows you how to do it with Apache/.htaccess, PHP, JavaScript, HTML, and more. Each redirect technique is briefly explained and includes ready-to-go, copy-&-paste examples. Just grab the code you need and use it in good health. May the redirects be with you!

Redirect URL with PHP

Redirecting with PHP is done using the header() function, for example:

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

All you need to do is change the URL to whatever you want. Note that it is important that this function be included at the beginning of the web page, before any HTML output. To learn more about customizing this technique, check out the PHP documentation.

To redirect via PHP after some period of time:

<?php
	header('Refresh:5; URL=http://example.com/');
	exit;
?>

Here we are redirecting to example.com after 5 seconds. Modify as desired.

Redirect URL with JavaScript

Here is the easiest way to redirect a URL with JavaScript:

<script type="text/javascript">
	document.location.href = 'http://example.com/';
</script>

Again, the only required modification is to change the URL according to your needs.

Redirect URL with HTML

Yes you can redirect the user to a new URL using plain old HTML. Here is an example:

<meta http-equiv="refresh" content="10; url=http://example.com/" />

This is referred to as a meta-refresh redirect. You can adjust the amount of time (in seconds) by changing 10 to whatever is necessary. Note that this redirect technique is frequently abused by spammers and other nefarious types, so be careful if you implement on a public site. In such cases, it is recommended to keep the refresh interval above 8 seconds to prevent any potential SEO penalties.

Redirect URL with Perl

Here are two ways to redirect URLs with Perl:

#!/usr/bin/perl
print "Location: http://example.com\n\n";
exit;

For more in-depth techniques, check out this article.

Redirect URL with ASP (VB Script)

To redirect a URL with ASP, add the following code:

<%@ Language=VBScript %>
<% response.status="301 moved permanently" Response.AddHeader "Location", "http://example.com" %>

Customize according to your needs.

Redirect URL with Apache’s mod_alias

The easiest way to redirect on Apache servers:

Redirect 301 /old-location.html http://example.com/new-location/

That code can be added to .htaccess or the Apache server configuration file. Here is the syntax for this technique:

[Directive] [Status Code] [Old URL] [New URL]

So you can change any of these factors as desired. For example, if we need to match the old URL dynamically, such that all of the following URLs are redirected:

http://example.com/old-directory/file-01.html
http://example.com/old-directory/file-02.html
http://example.com/old-directory/file-03.html
.
.
.

..we can use RedirectMatch instead of Redirect:

RedirectMatch 301 /old-directory/file-(.*)\.html http://example.com/new-directory/file-$1.html

Likewise, we can change the status code from 301 (permanent redirect) to 302 (temporary redirect). Or change it to any other valid status code as desired. Here is a guide to the regular expressions (regex) used in this RedirectMatch technique:

  • (.*) – matches any character (or no characters)
  • \. – matches a literal dot
  • $1 – returns the pattern matched by the first (.*)

For more information about Apache regex, check out my free PDF guide, .htaccess Character Definitions. Also check out Redirect URLs with .htaccess for more .htaccess-redirect techniques.

Redirect URL with Apache’s mod_rewrite

A more powerful way to redirect with Apache is to use it’s rewrite module, mod_rewrite. Here are some examples that can be added to .htaccess or the Apache configuration file.

Example 1: Redirect from wwww to non-www

This example redirects all www versions of our URLs to their equivalent non-www versions.

<IfModule mod_rewrite.c>
	RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
	RewriteRule (.*) http://example.com/$1 [R=301,L]
</IfModule>

This is referred to as canonicalization. Here are some notes about the regex used in this technique:

  • ^ – denotes the beginning of the requested URI
  • \. – matches a literal dot
  • $ – denotes the end of the requested URI
  • [NC] – makes the pattern match case-insensitive
  • (.*) – matches any character (or no characters)
  • $1 – matches the pattern from the parentheses (.*) in the RewriteRule
  • [R=301,L] – sends a 301 “Permanent” status code, and instructs Apache to stop processing the rule set

For more information about Apache regex, check out my free PDF guide, .htaccess Character Definitions.

Example 2: Redirect an entire domain

To redirect everything from the current domain to a new domain:

<IfModule mod_rewrite.c>
	RewriteRule ^/(.*) https://new-domain.tld/$1 [R=301,L]
</IfModule>

Likewise, to redirect all requests from a subdomain on the current site to the same subdomain on a new site:

<IfModule mod_rewrite.c>
	RewriteCond %{HTTP_HOST} (.*)\.old-domain\.tld [NC]
	RewriteRule ^/(.*) https://%1.new-domain.tld/$1 [R=301,L]
</IfModule>

Here are some notes about the regex used in these techniques:

  • ^ – denotes the beginning of the requested URI
  • (.*) – matches any character (or no characters)
  • $1 – matches the pattern from the parentheses (.*) in the RewriteRule
  • %1 – matches the first pattern from the parentheses (.*) in the RewriteCond
  • [R=301,L] – sends a 301 “Permanent” status code, and instructs Apache to stop processing the rule set

Note that, for either of these techniques to work properly, both domains must have the same file structure. So any directories and resources on the current domain also exist on the new domain. Otherwise you’ll get a bunch of 404 “Not Found” errors on the new domain. For more information about Apache regex, check out my free PDF guide, .htaccess Character Definitions.

Example 3: Redirect all HTML and PHP files

Here is another, more sophisticated mod_rewrite example:

<IfModule mod_rewrite.c>
	RewriteCond %{REQUEST_URI} ^/old-directory/(.*)\.(html|php)$ [NC]
	RewriteRule (.*) http://example.com/new-directory/%1.%2 [R=301,L]
</IfModule>

Here we are redirecting all requests for any HTML or PHP files located in /old-directory/. All matching requests are redirected to the same file located in /new-directory/. Some notes about the regex used in this redirect:

  • ^ – denotes the beginning of the requested URI
  • (.*) – matches any character (or no characters)
  • \. – matches a literal dot
  • (html|php) – matches either html or php
  • [NC] – makes the pattern match case-insensitive
  • %1 – matches the first pattern from the parentheses (.*) in the RewriteCond
  • %2 – matches the second pattern from the parentheses (html|php) in the RewriteCond
  • [R=301,L] – sends a 301 “Permanent” status code, and instructs Apache to stop processing the rule set

For more information about Apache regex, check out my free PDF guide, .htaccess Character Definitions. Also check out my tutorial on different ways to redirect with mod_rewrite.

Note: To redirect a URL based on its query string, check out my tutorial, Redirect Query String via .htaccess

Redirect 404 errors with Apache

Last but not least, here is a handy technique for redirecting all 404 “Not Found” errors to a specific URL.

ErrorDocument 404 http://example.com/wherever/

Simply change the URL to wherever and add the code to you site’s root .htaccess file, or add to the Apache configuration file. Learn more about customizing errors via .htaccess.

About the Author
Jeff Starr = Designer. Developer. Producer. Writer. Editor. Etc.
GA Pro: Add Google Analytics to WordPress like a pro.

8 responses to “How to Redirect URLs”

  1. Josh Arcadia 2017/04/25 1:47 pm

    The if it’s penalized by SEO, why don’t you add an extra line who says loading to the HTML solution?

    • Jeff Starr 2017/04/25 1:49 pm

      Interesting, but not sure if I understand your meaning.. would you mind clarifying, thanks.

      • Josh Arcadia 2017/04/25 1:53 pm

        8 – 10 seconds will make Visitors believe that there’s not a site there, so why don’t you add an extra line like:

        Loading…

      • Jeff Starr 2017/04/25 2:17 pm

        You mean add via meta tag or some other method..?

  2. Josh Arcadia 2017/04/25 2:30 pm

    well your html solution resolve me an old issue, since I tried .htaccess and php.ini and others… I added 2 lines to the html so the visitors don’t leave the site in the 8 – 10 segs period

    • Jeff Starr 2017/04/25 2:45 pm

      Ah now it all makes sense. Yes, that’s a good idea for HTML pages that are simply redirecting to a new location: just add a line of text to the page that says “Loading…” :)

  3. Josh Arcadia 2017/04/25 3:22 pm

    Yeah your example shows a blank page, and the visitor can get the idea that the site doesn’t exists, so I added:

    Loading…

    Anyways, thanks and glad you are back to WP :)

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
GA Pro: Add Google Analytics to WordPress like a pro.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.