1

Creating redirects as a client has merged many sites into a single site.

How would I set up a rule to redirect to a parent page if the child does not exist - rather than directly to 404.

Eg Redirect from

example.com/au/location1/staff (Does not exist)

to

example.com/au/location1

(there are a lot of these subpages which no longer exist)

2 Answers 2

2

If you want to do this in your .htaccess file to ensure an early redirect, the method is as follows.

First check if the page does not exist using the rewrite condition:

RewriteCond %{REQUEST_FILENAME} !-f

Next comes the rewrite rule for the page that does not exist

RewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L]

Putting this all together:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteRule ^/au/location1/(.*)$ http://example.com/au/location1/ [L]

Now if the page example.com/au/location1/staff exists then there will be no redirect, however if the page example.com/au/location1/staff does not exist the the user will be redirected to example.com/au/location1/.

Notice that this will apply to all child pages off example.com/au/location1/ i.e. any child pages that do not exist will redirect to the parent page.

I hope that I have interpreted your question correctly and that this helps.

1

Grab the 404 during the template_redirect and if it's not a file, redirect to the parent. Be careful, if someone is looking for site exploits then every 404 will render your home page.

function __404_template_redirect()
{
    if( is_404() )
    {
        $req = $_SERVER['REQUEST_URI'];

        if ( is_file( $req )) {
            return; // don't reduce perf by redirecting files to home url
        }

        // pull the parent directory and convert to site url
        $base_dir = dirname( $req );
        $parent_url = site_url( $base_dir );

        // redirect to parent directory
        wp_redirect( $parent_url, 301 );
        exit();
    }
}

add_action( 'template_redirect', '__404_template_redirect' );
1
  • Your solution proved to be very effective for me. I wanted exactly the same but instead of PHP I was searching for a solution in .htaccess but was unsuccessful. Now this code given by you is enhancing the beauty of the URLs of my website and redirecting the visitors to the right page. Thanks a million. Juniper Scott, theidioms.com Commented Feb 4 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.