Shoora
11/26/2018 - 1:38 AM

301 Redirects with .htaccess

301 Redirects with .htaccess

Below are some examples of how to deal with 301 redirects in .htaccess

Place the example code below into .htaccess

# Redirect an entire website
Redirect 301 / http://new-url.com
# Redirect permalinks
Redirect 301 /2011/02/old-permalink.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
<?php

/**
 * Force old permalinks to a new page.
 */
function wds_client_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', 'wds_client_301_redirect' );