WordPress rewrite rules don’t need ^?

For example this code

class My_Sitemap
{
    public static function install()
    {
        add_filter('rewrite_rules_array', array(__CLASS__, 'rewriteRules'), 1, 1);
        global $wp_rewrite;
        $wp_rewrite->flush_rules(false);
    }

    public static function rewriteRules($wpRules)
    {
        $rules = array(
            'sitemap.xml$' => 'index.php?pagename=my-sitemap',
        );
        return array_merge($rules, $wpRules);
    }

    public static function parseRequest($wp)
    {
        if (!isset($wp->query_vars['pagename'])) {
            return true;
        }
        if ($wp->query_vars['pagename'] !== 'minimal-xml-sitemap') {
            return true;
        }
        self::outputXML();
    }

    public static function outputXML()
    {
        echo 'hello';
    }
}

register_activation_hook(__FILE__, array('My_Sitemap', 'install'));
add_action('parse_request', array('My_Sitemap', 'parseRequest'));

the rewrite rule is sitemap.xml$, shouldn’t it be ^sitemap.xml$? If I go to mysite.com/asitemap.xml it doesn’t work, but mysite.com/sitemap.xml works. Which one is correct?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I just did a test and it seems like the rewrite rules imply ^ if you do not specify it. In my test I found:

rule 'foo' matched url 'foo'
rule '^foo' matched url 'foo'
rule 'foo' did not match url 'afoo'
rule '^foo' did not much url 'afoo'
rule '.*foo' matched url 'afoo'

So i had to explicitly add some matching regex at the start for it to match extra characters at the start.
‘foo’ did not match ‘afoo’

Personally, I like to be specific, so I think you’re right it makes sense to make your regex '^sitemap.xml$' because that’s what it will do.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x