WordPress Code Snippets

A fresh mix of code snippets and tutorials

Redirect URLs with .htaccess

118

Here is a quick cheat-sheet for redirecting URLs with .htaccess.

Redirect a web page or directory

Redirect a specific page:

Redirect /old-resource.html http://example.com/path/to/new-resource.html

Redirect entire directory to new page:

RedirectMatch /old-directory/ http://example.com/path/to/new-directory

Redirect a web page to a directory

To redirect any page to a directory:

Redirect 301 /page.html http://example.com/directory/

Likewise, to redirect a specific directory to another directory:

RedirectMatch 301 /directory http://example.com/directory/

Redirect entire site

If you move your site to another domain, and want to redirect all URLs to their equivalent URLs on the new domain, add this to the root .htaccess file on the old domain:

Redirect 301 / http://example.com/

Or, if you simply want to redirect all URLs from the old domain to a specific page on the new domain (such as the homepage), add this to the root .htaccess file on the old domain:

RedirectMatch 301 / http://example.com/specific-page.html

Redirect from one file type to another

If you change the extension of your web pages, say from .html to .php, with the file names remaining the same, add this to .htaccess:

RedirectMatch 301 /(.*)\.html http://example.com/$1.php

Alternate redirect methods

Redirect via <meta> tag in the document <head>:

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

To redirect via PHP, add this to the very top of any web page:

<?php
	header('HTTP/1.1 301 Moved Permanently');
	header('http://example.com/');
?>

Redirect from one page to another

Note that in these examples, we’re redirecting with a 301 “Permanent” response. This may be changed to any other valid status, such as a 302 “Temporary” response. For more info, see HTTP/1.1 Status Code Definitions.

Learn more

.htaccess made easy


Show Support

Like our new Facebook Page to show support!