How can i redirect one url to another url using .htaccess or add_rewrite_rule

I’m honestly struggling to comprehend this failure state – I believe I’ve reproduced the issue locally, and in my testing the RewriteRule directive hits but then WordPress processes the original input, resulting in a fairly catch-all attachment rewrite producing a query for a non-existent attachment. I may continue playing with it to try and figure out what’s going on.

In the meantime, I think the root of the issue is complexity introduced by using a URI as the target of the RewriteRule. Using a file path seems to alleviate the problem:

RewriteRule ^page-check-([A-Z0-9_-]+)/highlights/?$ index.php?pagename=page-highlights&id=$1 [L]

Regarding the use of add_rewrite_rule(), I have a few notes:

  • When you use a target which does not start with index.php, WordPress will write the rule to the .htaccess file and implicitly begin the pattern with the ^ character – thus, starting a pattern with ^ while using a URI target can result in malformed rule beginning with ^^.
  • Instead of positional references to matches such as $1, WordPress uses the syntax $matches[1].
  • Flushing rewrite rules is a fairly expensive operation – I’d strongly recommend against flushing them in routine hook!

The above in mind, an add_rewrite_rule() with using a filepath target akin to the above RewriteRule directive would look as such:

add_action('init', 'ao_add_rewrite_rule');

function ao_add_rewrite_rule() {
   add_rewrite_rule('^page-check-([A-Z0-9_-]+)/highlights/?$', 'index.php?pagename=page-highlights&id=$matches[1]', 'top');
}