How to prevent automatic redirection of 404 errors and "incorrect" URLs?

Wordpress has a feature whereby it will automatically redirect your URLs if it percieves them to be written wrongly. Here is an example: I have a page called my-page

If I go to:

www.mysite.com/something/my-page/

it will immediately redirect me to

www.mysite.com/my-page/

as nothing exists at the first URL.

How can I turn this feature off, and instead just get a 404 if incorrect URL's are typed in?

Topic rel-canonical urls redirect 404-error Wordpress

Category Web


You can disable permalink guessing for 404s without disabling redirection of canonical URLs by adding the following line somewhere in your code (eg. in functions.php):

add_filter('do_redirect_guess_404_permalink', '__return_false');

Relevant functions in the Wordpress code are redirect_canonical and redirect_guess_404_permalink in wp-includes/canonical.php.


As Ash suggested, you can turn off the feature by using the following code:

remove_action('template_redirect', 'redirect_canonical');

In looking at the redirect_canonical function in canonical.php, it would appear you can also modify the behavior with your own filter.

At the end of the redirect_canonical() function, there is a call to filter the final answer:

$redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );

So you could write your own filter to modify the final redirection or return null to stop the redirection, based upon the input, thus turning off the feature for a particular URL or a subset of URLs.


This worked for me:

remove_action('template_redirect', 'redirect_canonical');

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.