wpexpertsio / password-protected

Password protect your WordPress site quickly and simply
https://wordpress.org/plugins/password-protected/
69 stars 63 forks source link

HELP - SITE REDIRECTING TO HOMEPAGE #169

Closed luhvleedesignco closed 3 years ago

luhvleedesignco commented 4 years ago

I am seeing this same issue over and over again and not seeing it resolved. How do we get the plugin to stop redirecting to the homepage? Flushing cache resolves the issue but we can't do this every day to ensure the site is working properly.

rxnlabs commented 4 years ago

@luhvleedesignco This is due to how the plugin handles the redirect that takes place when you are not logged in. Even though the plugin does do a 302 redirect to the login page, the 302 redirect can get cached by the browser since a 302 redirect does not mean that the browser won't cache the page. Your browser is caching original request page e.g. https://example.com/my-requested-page and the plugin is redirected users to https://example.com/password-protected=login&redirect_to=https%3A%2F%2Fexample.com%2Fmy-requested-page. After you successfully login, you are taken to https://example.com/. When you try to go to your original page https://example.com/my-requested-page, your browser thinks that https://example.com/my-requested-page should be redirected to https://example.com/.

A workaround fix is to add this code to your theme's functions.php file to prevent that redirect caching from taking place.

/**
Force the password protect redirect to send a No Cache header when the redirect takes place.

This prevents the user's browser from caching the redirect and making the browser think that redirect page is the original page that the user wanted to go to.
*/
function password_protect_fix( $location, $status ) {
    if ( is_admin() ) {
        return $location;
    }

    $query_args = wp_parse_url( $location, PHP_URL_QUERY );

    if ( ! empty( $query_args ) && false !== strpos( $query_args, 'password-protected' ) ) {
        nocache_headers();
    }

    return $location;
}
add_filter( 'wp_redirect', 'password_protect_fix', 10, 2 );
benhuson commented 3 years ago

PR merged. Will be in next release.