wordpresshttp-redirectsubdirectory

Setting up redirect in header.php (subdirectory to an external website)


I'd like to know how to do this using header.php (WordPress) or any other method. Basically, I want to set up a redirect from a subdirectory page (e.g. "/my-ebook/") to an external website (e.g. Gumroad).

So, when people visit "/my-ebook/", they're redirected to my Gumroad profile page, for example. I know a plugin can do this, but want to know a way to do this without using a plugin. Thank you in advance.


Solution

  • The template_redirect action is probably the most appropriate action to use, but you could probably use an mu-plugin to run as early as possible.

    Here's with the template_redirect action (add to your theme's functions.php):

    add_action( 'template_redirect', static function () {
        if ( empty( $_SERVER['REQUEST_URI'] ) ) {
            return;
        }
    
        $redirect = false;
    
        foreach ( array( '/my-ebook/', '/my-product/' ) as $needle ) {
            if ( str_contains( $_SERVER['REQUEST_URI'], $needle ) ) {
                $redirect = true;
                break;
            }
        }
    
        if ( ! $redirect ) {
            return;
        }
        
        nocache_headers();
        
        wp_redirect( ... );
    
        exit;
    } );
    

    For an mu-plugin, take out the code within the action's callback and place it in wp-content/mu-plugins/gumroad-redirect.php:

    <?php
    
    if ( empty( $_SERVER['REQUEST_URI'] ) ) {
        return;
    }
    
    $redirect = false;
    
    foreach ( array( '/my-ebook/', '/my-product/' ) as $needle ) {
        if ( str_contains( $_SERVER['REQUEST_URI'], $needle ) ) {
            $redirect = true;
            break;
        }
    }
    
    if ( ! $redirect ) {
        return;
    }
    
    nocache_headers();
    
    wp_redirect( ... );
    
    exit;