Prevent WordPress Redirecting to Nearest Matching URL
WordPress comes with a nifty feature which enables it to navigate to the closest matching URL if the one typed in doesn’t exist. This reduces the chance of a user getting presented with a 404 page if they’ve slightly mistyped a page’s URL.
An example of this would be; imagine we have a page with the following URL:
But the user types in:
In this scenario it would redirect the user to the closest matching page.
It’s a pretty cool feature and one I use myself on my own site if I can’t quite remember the full URL to a page. I can just type in the first part of the URL and WordPress will redirect me accordingly if it finds a match.
Turning It Off
Yes, the above is great, but what if we want to disable it? On a site recently I needed to do exactly this when I was using URL’s that didn’t relate to pages and, instead, jumped to different parts of a single page site.
The solution was to add the below code to my theme’s functions.php file:
Once the above code had been added, WordPress no longer tried to send me to the page with the closest URL. This is probably a very rare scenario but it’s good to know that this can be disabled with a single line of code.