Using WordPress ‘mod_rewrite_rules’ PHP filter

The mod_rewrite_rules WordPress PHP filter allows you to modify the list of rewrite rules formatted for output to an .htaccess file.

Usage

add_filter('mod_rewrite_rules', 'my_custom_mod_rewrite_rules');
function my_custom_mod_rewrite_rules($rules) {
    // Your custom code here
    return $rules;
}

Parameters

  • $rules (string): The mod_rewrite rewrite rules formatted for .htaccess.

More information

See WordPress Developer Resources: mod_rewrite_rules

Examples

Remove a specific rule

Remove a specific rewrite rule from the list.

add_filter('mod_rewrite_rules', 'remove_specific_rule');
function remove_specific_rule($rules) {
    // Remove a specific rule
    $rule_to_remove = 'RewriteRule ^index\.php$ - [L]';
    $rules = str_replace($rule_to_remove . "\n", '', $rules);
    return $rules;
}

Add a custom rule

Add a custom rewrite rule to the list.

add_filter('mod_rewrite_rules', 'add_custom_rule');
function add_custom_rule($rules) {
    // Add a custom rule
    $custom_rule = 'RewriteRule ^custom-path/?$ /index.php?p=123 [L]';
    $rules = $custom_rule . "\n" . $rules;
    return $rules;
}

Change the base of the rewrite rules

Change the base of the rewrite rules to a subdirectory.

add_filter('mod_rewrite_rules', 'change_base_of_rewrite_rules');
function change_base_of_rewrite_rules($rules) {
    // Change the base to a subdirectory
    $rules = str_replace('RewriteBase /', 'RewriteBase /subdirectory/', $rules);
    return $rules;
}

Disable rewriting for a specific directory

Disable rewriting for a specific directory by adding a rule.

add_filter('mod_rewrite_rules', 'disable_rewrite_for_directory');
function disable_rewrite_for_directory($rules) {
    // Disable rewriting for a specific directory
    $disable_rule = 'RewriteRule ^example-directory/ - [L]';
    $rules = $disable_rule . "\n" . $rules;
    return $rules;
}

Change the rewrite conditions for specific rules

Change the rewrite conditions for specific rules based on a custom condition.

add_filter('mod_rewrite_rules', 'change_rewrite_conditions');
function change_rewrite_conditions($rules) {
    // Change the rewrite conditions for specific rules
    $search = 'RewriteCond %{REQUEST_FILENAME} !-f';
    $replace = 'RewriteCond %{REQUEST_FILENAME} !-f [OR]' . "\n" . 'RewriteCond %{REQUEST_URI} ^/custom-condition/';
    $rules = str_replace($search, $replace, $rules);
    return $rules;
}