Does WP Have a Function To Generate .htaccess RewriteCond?

I know that I can edit .htaccess manually and add a RewriteCond statement inside, but I need to build a plugin that does this the proper way by using WP rewrites which then get pushed into .htaccess with flush_rewrite_rules(). I need RewriteCond in this case.

Does WP have some obscure function that lets me push a RewriteCond statement into the .htaccess?

Related posts

Leave a Reply

1 comment

  1. In short yes…

    ‘External’ Rewrite Rules

    If in add_rewrite_rule the rule is isn’t directed to index.php then the rule is treated as an ‘external’ rule (i.e. not to be processed by WordPress’ internal handing of rewrites) and instead written to the .htaccess file. I.e. if:

    add_rewrite_rule('^nutrition/([^/]*)/([^/]*)/?','somethingelse.php?p=12&food=$1 &variety=$2','top');
    

    is used instead of

    add_rewrite_rule('^nutrition/([^/]*)/([^/]*)/?','index.php?p=12&food=$matches[1]&variety=$matches[2]','top');
    

    Then the rule is recognised as a non (internal) WordPress rule and is added the .htaccess file rather than dealt with internally. Note for ‘external’ rules – you use $1 instead of $matches[1];

    Adding custom rules to .htaccess

    When rewrite rules are flushed, the .htacess file is written to. There is a hook which filters what is actually written. mod_rewrite_rules

    function wpse50631_htaccess( $rules ){
       //Append or preppend extra rules.
       return $rules;
    }
    add_filter('mod_rewrite_rules', 'wpse50631_htaccess');
    

    The codex has this to say:

    mod_rewrite_rules() is the function that takes the array generated by rewrite_rules() and actually turns it into a set of rewrite rules for the .htaccess file. This function also has a filter, mod_rewrite_rules, which will pass functions the string of all the rules to be written out to .htaccess, including the <IfModule> surrounding section. (Note: you may also see plugins using the rewrite_rules hook, but this is deprecated).