Weird post pagination url redirect

That’s actually the default behavior when the post does not have any page breaks (i.e. the <!--nextpage--> tag).

More specifically, in redirect_canonical(), WordPress only performs a redirect if the post has the page break tag — and that the page number is invalid (e.g. requesting for page #3 when there are only 2 pages). Otherwise (i.e. no page breaks), those paginated URLs/requests are seen as valid and WordPress doesn’t do any redirects except for the first page (e.g. /hello-world/1) because the content is considered a duplicate of /hello-world.

So for those “valid” requests, if you want to redirect them to the first page, you can use the pre_handle_404 hook like so:

add_filter( 'pre_handle_404', function ( $bool ) {
    if ( is_singular( [ 'post', 'page', 'etc' ] ) && get_query_var( 'page' ) &&
        false === strpos( get_queried_object()->post_content, '<!--nextpage-->' )
    ) {
        wp_redirect( get_permalink( get_queried_object() ) );
        exit;
    }

    return $bool;
} );

You can also use the wp hook, but the pre_handle_404 seems better since it’s called first:

add_action( 'wp', function ( $wp ) {
    if ( is_singular( [ 'post', 'page', 'etc' ] ) && get_query_var( 'page' ) &&
        false === strpos( get_queried_object()->post_content, '<!--nextpage-->' )
    ) {
        wp_redirect( get_permalink( get_queried_object() ) );
        exit;
    }
} );

And I’m using is_singular() to target singular requests like single Post (post type post) pages.

tech