Skip to content

301 Redirects with .htaccess

After I dumped my database and blew up my site, I wanted to resurrect my most popular content. I needed to setup 301 redirects so both users and Google could find my (old) content in its (new) location.

The structure looks like this:

301-redirect-instructions

Redirect an entire website:

Redirect 301 / http://new-url.com

Redirect an old permalink:

Redirect 301 /2011/02/old.html http://new-url.com/same-content-new-permalink/

Redirect WordPress local development uploads, to dev/prod server:

RedirectMatch 301 ^/wp-content/uploads/(.*) http://mylivesite.com/wp-content/uploads/$1

You could also leverage WordPress and a quick function:

/**
 * Force old permalinks to a new page.
 */
function grd_301_redirect() {
	// Get the URL.
	$url = untrailingslashit( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
	// Redirect to the correct page!
	if ( is_404() && ( false !== strpos( $url, 'old-page-url' ) ) ) {
		wp_redirect( 'https://new-url.com/new-page-url', 301 );
	}
}
add_action( 'template_redirect', 'grd_301_redirect' );

About Greg Rickaby

Director of Engineering @WebDevStudios / Author & Tech Editor @ForDummies / @WordPress Contributor / @gatsbyjs Maintainer / Follow Greg on Twitter

3 Comments

  1. Gautam Doddamani on May 22, 2013 at 11:06

    haha lol dude i have linked to two of your posts…and they showed up as broken and then i checked wats the deal and landed on to this post…here are those two posts…

    https://gregrickaby.com/2012/02/how-to-display-and-highlight-code-in-wordpress-without-a-plug-in.html

    https://gregrickaby.com/2010/04/how-to-use-jquery-lazy-load-in-thesis.html

    please fix em with a redirect too! thanks….and the new site design is awesome 😀

  2. Flaudísio Tolentino on May 30, 2013 at 08:18

    Just a suggestion: RedirectMatch 301 ^/\d{4}/\d{2}/(.+)(\.html)$ https://gregrickaby.com/$1/
    🙂

  3. Nigeria News (@naijalocalnews) on May 31, 2013 at 19:31

    This is a very nice post on htaccess redirect . Your article is great, i like it

Leave a Comment