0

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)

1

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.

0

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' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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