Viewing 2 replies - 1 through 2 (of 2 total)
  • You can use the Redirection plugin for WordPress to automatically redirect the shorter URL to the longer URL.

    To use the Redirection plugin:

    Install and activate the Redirection plugin.
    Go to Tools > Redirection in your WordPress dashboard.
    Click on the Add New button.
    In the Source URL field, enter the shorter URL (/my-subpage).
    In the Target URL field, enter the longer URL (/parent-page/my-subpage).
    Leave the other settings as they are and click on the Add Redirect button to save the redirect.
    The plugin will now automatically redirect any traffic going to the shorter URL to the longer URL.

    Alternatively, you can use the WordPress Rewrite API to create custom rewrite rules for your URLs. This will allow you to define the redirect rules directly in your theme’s functions.php file.

    To use the Rewrite API:

    Open your theme’s functions.php file.
    Add the following code to the file:
    Copy code

    function custom_rewrite_basic() {
    add_rewrite_rule(‘^my-subpage/?’, ‘index.php?pagename=parent-page/my-subpage’, ‘top’);
    }
    add_action(‘init’, ‘custom_rewrite_basic’);

    This code will create a custom rewrite rule that will redirect any traffic going to /my-subpage to /parent-page/my-subpage.

    You can add as many rewrite rules as you need by adding more lines of code similar to the one above.

    Note that you may need to flush the rewrite rules after adding them by going to Settings > Permalinks in your WordPress dashboard and clicking on the Save Changes button.

    I hope this helps! Let me know if you have any questions.

    Thread Starter te-deum

    (@te-deum)

    Hello,

    Thank you for the complete response !
    By the way, I don’t want to use specific configuration and I want it to work for the whole website.

    So here is my solution because no other options :

    function check_post_url( $post ) {
    	// Current page infos
    	$current_url  = "https://";
    	$current_url .= $_SERVER["HTTP_HOST"];
    	$current_url .= $_SERVER["REQUEST_URI"];
    	$post_url     = get_permalink($post->ID);
    	// Check url vs post url
    	if(!str_starts_with($current_url, $post_url)) {
    		// Add query string if any
    		if(!empty($_SERVER['QUERY_STRING']))
    			$post_url .= '?' . $_SERVER['QUERY_STRING'];
    		header("HTTP/1.1 301 Moved Permanently");
    		header("Location: $post_url");
    		exit();
    	}
    }
    add_action( 'the_post', 'check_post_url' );

    I force HTTPS because htaccess have rules to redirect whole urls to https if not.
    It work as expected.

    There may be a better action hook to use. If so, let me know ??

    • This reply was modified 2 years, 1 month ago by te-deum.
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Page in subfolder display also on root’ is closed to new replies.