This tutorial explains how to disable automatic redirection for canonical URLs in WordPress. Here I will mention a simple code snippet that you can include in WordPress functions to prevent automatic redirection. After that, your WordPress website will not make redirects.
When you request a URL that doesn’t exist, e.g. https://www.ilovefreesoftware.com/amaras, WordPress returns 404. But, if that URL is a prefix of some existing post or page, then it instead returns a 301 redirect to the post or page(e.g. https://www.ilovefreesoftware.com/free).
This behavior is annoying and sometimes can mark your website flagged on search engines. You can see this in the video above.
To prevent the this behavior of WordPress, you have to install a simple code snippet that I have mentioned below. You don’t need any coding knowledge to configure this and after you add this simple code snippet, your WordPress site will simply return 404 when someone adds a word to any URL which is a prefix for some other post.
Follow the steps below to turn off automatic redirection on WordPress.
How to Disable Automatic Redirection for Canonical URLs in WordPress?
- Login to the WordPress Dashboard and then go to the theme editor. To do that, you go to Appearance > Theme File Editor.
- From theme files on the right, open the Theme Function file aka “functions.php“.
- Paste the following code snippet at the end.
add_filter('redirect_canonical', 'no_redirect_on_404');
function no_redirect_on_404($redirect_url)
{
if (is_404()) {
return false;
}
return $redirect_url;
}
- Save changes by clicking on “Update File” button and exit.
Now, when you try to add a keyword at the end of a canonical URL on the website which is a prefix for some other post then it will simply return a 404 error. I have shown this behavior in the above video as well.
If you have multiple websites which are running on WordPress then you can simply follow the steps the disable automatic redirection. And in case you don’t need it later then you can simply remove the code from the function file.
Final thoughts:
An automatic redirections is performed in WordPress using the htaccess-file function it has to redirect if the filename matches with an existing page or blog post. But the above steps I have mentioned above can help you disable this behavior. So, if you are looking for a solution for this problem then you are at the right place.