Home > Enterprise >  Redirect all pages except home page htaccess
Redirect all pages except home page htaccess

Time:06-24

I have a Wordpress website and I'm trying to redirect all pages to a landing page on the same domain except for the home page. I tried many solutions found around internet but none of them worked.

What I need is:

  • Home page and wp-admin page should always be reachable (example.com and examplecom/wp-admin)
  • All the other pages should be redirected with a 302 code to example.com/redirect-page

Thanks in advance

CodePudding user response:

There might be a better solution, but you could try this:

you could use $_SERVER['REQUEST_URI'] to get part of the url:

URL: www.example.com/abc/de

output $_SERVER['REQUEST_URI']: /abc/de

Then you can use <meta http-equiv="refresh" content="0; url=http://example.com/redirect-page" /> to redirect.

So something like this:

if($_SERVER['REQUEST_URI'] != "" && $_SERVER['REQUEST_URI'] != "/wp-admin") {
   echo '<meta http-equiv="refresh" content="0; url=http://example.com/" />';
}

CodePudding user response:

You can use filter that would allow you to create an exception with code which handles website redirect based on current configuration.

https://plugins.trac.wordpress.org/browser/simple-website-redirect/trunk/SimpleWebsiteRedirect.php#L113

Something like this :

add_filter(
    'simple_website_redirect_should_redirect',
    function( $should_redirect, $url ) {

        if( home_url() === $url ) {
            return false;
        }

        return $should_redirect;   
    },
    10,
    2
);

Htaccess : https://stackoverflow.com/a/38594600/19168006

Edit : You need to add that code to your theme functions.php

This is the second solution: Perhaps not as elegant as a theoretical, functional .htaccess solution (if it exists).

// Redirect entire site except one page ID

add_action( 'template_redirect', 'pc_redirect_site', 5 );
function pc_redirect_site(){
    
    $url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . $_SERVER[ 'REQUEST_URI' ];
    $current_post_id = url_to_postid( $url );
    if ( ! is_admin() && ! is_page( 9999 )) { // Excludes page with this ID, and also the WordPress backend
        $id = get_the_ID();
        wp_redirect( 'http://example.com', 301 ); // You can change 301 to 302 if the redirect is temporary
        exit;
    } 
}

If you don’t want to redirect the admin section, remove ! is_admin() && Replace http://example.com with the destination you wish to redirect traffic to By default this performs a 301 (permanent) redirect; if you intent for this to be temporary, change 301 to 302 Obviously swap out 9999 for the page ID you wish to exclude.

Note, however, that if you aren’t using a child theme and you have auto-updates on, it will likely be overwritten at some point when your theme forces an update and you’ll have to update it again.

More explanition : here

  • Related