0

I have a parent page with the URL

example.com/the-boats

And then child pages like so:

the-boats/story
the-boats/cast
the-boats/articles
etc...

Many visitors type

example.com/boats
example.com/cast

So when they do this I want to redirect them to

/the-boats
/the-boats/story
etc...

I cannot figure out how to do this. I've tried 3 strategies thus far

function custom_rewrite_basic() 
{

add_rewrite_rule('^boats/?$',   'index.php?pagename=the-boats/$matches[2]', 'top'); 
flush_rewrite_rules();
}
add_action('init', 'custom_rewrite_basic');

and...

add_filter('redirect_canonical', 'my_redirect_canonical', 10, 2);
function my_redirect_canonical($redirect_url, $requested_url) {
  if ( $requested_url == 'https://example.com/boats') { 
    $redirect_url = 'https://example.com/the-boats';
}
return $redirect_url;
}

And also I've tried using the Redirection Plug-in.

Now what happens in each case is that it redirects to the content of

/the-boats

BUT the URL remains /boats

...which is not good. Worse yet, when I type in

/boats/story

...it still redirects to the content of

/boats

...and yet worser still :D it seems to screw up the Permalinks so that when I remove any of this code, I have to rebuild the Permalinks to get the original links starting with 'the-boats' to work again.

I'm using Yoast SEO 'free' if that has any impact on this.

So... what am I doing wrong? How do I get the redirects to work properly AND have the URL in the address bar to appear properly?

4
  • 1
    calling flush_rewrite_rules is very expensive, it'll slow your pages down a lot, and can cause problems with rewrite rules related to ordering
    – Tom J Nowell
    Oct 3, 2017 at 23:04
  • Good to know. Without flush_rewrite_rules() the add)rewrite_rules() hook didn't seem to work.
    – jchwebdev
    Oct 4, 2017 at 0:52
  • 1
    Rewrites and redirection are two different things. Rewrite rules map URL patterns to query vars. If you are expecting to visit one URL and get sent to a different URL which is reflected in the URL bar, that is redirection and has nothing to do with rewrite rules.
    – Milo
    Oct 4, 2017 at 3:36
  • 1
    Also, you only need to flush rewrite rules when they change, saving permalinks in the admin area should be enough, so you never need to call flush rewrite rules
    – Tom J Nowell
    Oct 4, 2017 at 10:58

1 Answer 1

0

Does this simple .htaccess rule solve your problem?

RewriteRule ^/boats/(.*)$ https://www.example.com/the-boats/$1 [R=301,NC,L]

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.