How to avoid automatic redirection or canonical redirection in WordPress?

Overview Overview

WordPress redirects the incoming links to the proper URL based on the site url.

Search engines consider the link www.somedomain.com and somedomain.com to be two different URLs when they both go to the same location.

This SEO enhancement prevents penalties for duplicate content by redirecting all incoming links to one or the other.

Prevents redirection for feeds, trackbacks, searches, and admin URLs. Does not redirect on non-pretty-permalink-supporting IIS 7+, page/post previews, WP admin, Trackbacks, robots.txt, searches, or on POST requests.

We will also attempt to find the correct link when a user enters a URL that does not exist based on the exact WordPress query. Will instead try to parse the URL or query in an attempt to figure the correct page to go to.

Issue Issue

I don’t think this is an issue. But, most of the cases we don’t want such redirection.

Let’s check it by a simple example, Suppose, We have a fresh WordPress setup.

If I visit the page

https://maheshwaghmare.com/s

Here, My domain name is http://localhost/dev.new/ and I have just added the /s.

WordPress redirect the above URL to

https://maheshwaghmare.com/plugins/sample-data/

This is because WordPress handles this in action template_redirect and the function redirect_canonical which is @since 2.3.0.

Solutions Solutions

I have found two ways to fix this issue (maybe 🙂 )`.

Solution 1: Solution 1:

If you don’t want such automatic redirection then you can remove the redirect_canonical action.

E.g.

remove_action( 'template_redirect', 'redirect_canonical' );

Note: The above code affects all your currently existing post types. If you want to disable it for a specific situation then you can go with Solution 2.

Solution 2: Solution 2:

Since WordPress 2.3.0 version we have a filter redirect_canonical.

Completely disable it redirection with the filter.

add_filter( 'redirect_canonical', '__return_false' );

Or

To check the specific request or redirect and enable or disable it. The filter redirect_canonical accepts 2 parameters.

  • $redirect_url – It is a redirect URL.
  • $requested_url – It is a requested URL.

We can use:

add_filter( 'redirect_canonical', 'prefix_debug_redirection', 10, 2 );

function prefix_debug_redirection( $redirect_url = '', $requested_url = '' ) {

    /*
    // Do something if REDIRECT url match.
    if( '/mylink/' === $redirect_url ) {
        return '';
    }

    // Do something if REQUEST url match.
    if( '/mylink/' === $requested_url ) {
        return '';
    }
    */

    return $redirect_url;
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top
%d bloggers like this: