WordPress appears to rewrite URLs, displaying Pages under the incorrect URL.
Example. I have a page called "Emotion" with the slug /emotion/
On the front-end it should appear as the following URL ; example/learning/domains/emotion/
That is, there is a child/parent relationship defined within the Pages section of the website, as shown in that URL. Unfortunately, wordpress chooses to show anyone the page, no matter what URL you type in
Examples;
None of these are real paths. I expect to see a 404 page.
I've done research already, and tried the below two. The first one used to work in WP versions prior to v6. Now neither work.
remove_filter('template_redirect', 'redirect_canonical');
add_filter( 'redirect_canonical', 'disable_redirect_canonical', 10, 2 ); function disable_redirect_canonical( $redirect_url ) { return false; }
How do I disable this rewrite rule?
WordPress appears to rewrite URLs, displaying Pages under the incorrect URL.
Example. I have a page called "Emotion" with the slug /emotion/
On the front-end it should appear as the following URL ; example.com/learning/domains/emotion/
That is, there is a child/parent relationship defined within the Pages section of the website, as shown in that URL. Unfortunately, wordpress chooses to show anyone the page, no matter what URL you type in
Examples;
None of these are real paths. I expect to see a 404 page.
I've done research already, and tried the below two. The first one used to work in WP versions prior to v6. Now neither work.
remove_filter('template_redirect', 'redirect_canonical');
add_filter( 'redirect_canonical', 'disable_redirect_canonical', 10, 2 ); function disable_redirect_canonical( $redirect_url ) { return false; }
How do I disable this rewrite rule?
After doing some research, I have found the answer, albeit with a small limitation.... only shows the page with a trailing slash. This is perhaps technically correct url display so I'll deal with it.
I found the solution buried in this similar Question Disable Wordpress URL auto complete
The CORRECT solution is by David Vielhuber - strangely is not voted as the correct solution. The upvoted solution perhaps worked for older WordPress versions, but no longer since WP v6.x.
To disable WordPress Canonical Redirect (to Nearest Matching URL) and force 404 Page... Add the following code to your child theme functions.php file.
// Disable WordPress canonical redirect to nearest matching URL and force 404 Page
// ---------------------------------
add_filter( 'redirect_canonical', function( $redirect_url ) {
$url = 'http'.((isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'s':'').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if( $redirect_url !== $url ) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
nocache_headers();
}
return false;
});