Search code examples
phpwordpress.htaccesshttp-redirect

Redirect only WordPress homepage with a 301 redirect


I have a blog, lets say example.com and another blog installed in example.com/np which is not multisite but a different WordPress installation.

What I want is to redirect example.com homepage only to example.com/np. It would be great if that redirection is a 301 moved permanently redirection.

If I place the 301 redirection in WordPress header file, header.php, it will redirect every page. And if I check if the page is home and try a 301 redirection that's not possible because header redirection should be placed at top.

How to achieve this?


Solution

  • Since you're in the context of WordPress, you can utilize its redirect functionality.

    Like this ( in functions.php ):

    function redirect_homepage() {
        if( ! is_home() && ! is_front_page() )
            return;
    
        wp_redirect( 'http://redirect-here.com', 301 );
        exit;
    }
    
    add_action( 'template_redirect', 'redirect_homepage' );