Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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).

share|improve this answer
    
Aha! The main thing is that last section you have in vanilla here. This is where I can edit the string that gets written and this is where I can add RewriteCond. –  Volomike Apr 30 '12 at 12:34
1  
@Volomike It's wise to note that not every wordpress install allows wordpress to directly modify the .htaccess, so don't bank on being able to...at the very least throw a warning and some instructions to do it manually if it can't be done programatically. –  m0r7if3r Apr 30 '12 at 12:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.