htaccess: Remove trailing slash from URL ending with .xml/ only

I need to remove trailing slash from URLs ending with .xml/ only .. For this purpose I’ve created a Rewrite Condition and Rule which is working perfectly fine for the test link http://website.com/test.xml/

Test Link: http://htaccess.mwl.be?share=6fe08232-438a-53fa-8f1a-1f7f69b77b6f

The problem is when I place the rule in WordPress .htaccess file, it doesn’t work at all! Seems like WordPress or YOAST Permalink structure is overriding the rule .. please help!

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_URI} /(.*).xml/$
RewriteRule ^ /%1.xml [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Note:

Please note that this is not a physical file .. using rewrite rules to generate sitemap on the run! This is a wordpress page in fact!

add_rewrite_rule('([^/]*)-placeholder.xml','index.php?page_id=123&custom‌​-slug=$matches[1]','‌​top');

3 Answers
3

If you’re outputting a sitemap, there’s no reason to wait for the query for your page- which is what is producing the redirect.

Hook an earlier action and you won’t need anything to counter the trailing slash, because it won’t happen-

EDIT

Here’s a complete version with registering query vars, rules, and parse_request action:

// add the custom query vars
// WordPress will not parse query vars in rules
// if they are not added to the list of valid query vars
function wpd_sitemap_query_var( $vars ){
    $vars[] = 'svc-slug';
    $vars[] = 'svc-offset';
    return $vars;
}
add_filter( 'query_vars', 'wpd_sitemap_query_var' );

// add the rules
function wpd_sitemap_rewrite_rules() {
    add_rewrite_rule(
        '([^/]*)-svc-([0-9]+).xml',
        'index.php?page_id='.get_field('dynamic_sitemap','option').'&svc-slug=$matches[1]&svc-offset=$matches[2]',
        'top'
    );
    add_rewrite_rule(
        '([^/]*)-svc.xml',
        'index.php?page_id='.get_field('dynamic_sitemap','option').'&svc-slug=$matches[1]',
        'top'
    );
}
add_action('init', 'wpd_sitemap_rewrite_rules', 10, 0);

// intercept the query and test if our query var is set
// this means one of our rules matched and we should show the sitemap
function wpd_sitemap_parse_request( $query ){
    if( isset( $query->query_vars['svc-slug'] ) ){
        echo '<pre>';
        print_r( $query->query_vars );
        echo '</pre>';

        // halt further execution after sitemap is output
        die;
    }
}
add_action( 'parse_request', 'wpd_sitemap_parse_request' );

Leave a Comment