mod_rewrite_rules
Allows you to change, add, or remove any rules in the .htaccess file.
For example, this hook can be used to:
- Change existing pretty permalink (URL rewrite) rules.
- Add custom redirect or URL rewrite rules.
- Create a rule for 301 redirects from HTTP to HTTPS.
- Add any other lines to the
.htaccessfile.
Rules are added to .htaccess with the insert_with_markers() function.
Usage
add_filter( 'mod_rewrite_rules', 'wp_kama_mod_rewrite_rules_filter' );
/**
* Function for `mod_rewrite_rules` filter-hook.
*
* @param string $rules mod_rewrite Rewrite rules formatted for .htaccess.
*
* @return string
*/
function wp_kama_mod_rewrite_rules_filter( $rules ){
// filter...
return $rules;
}
- $rules(string)
- The current list of rewrite rules for the
.htaccessfile.
Examples
#1 Add HTTP-to-HTTPS redirect rules to .htaccess
Code from the Mihdan: HTTP To HTTPS Via Htaccess plugin.
add_filter( 'mod_rewrite_rules', function ( $rules ) {
$https = "\n";
$https .= "# Redirect from HTTP to HTTPS.\n";
$https .= "<IfModule mod_rewrite.c>\n";
$https .= "RewriteEngine On\n";
$https .= "RewriteCond %{HTTPS} off\n";
$https .= "RewriteCond %{HTTP:X-Forwarded-Proto} !https\n";
$https .= "RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n";
$https .= "</IfModule>\n";
$https .= "\n";
return $https . $rules;
} );
The resulting .htaccess contains:
# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress"
# are dynamically generated and should be modified only via WordPress filters.
# Any manual changes between these markers will be overwritten.
# Redirect from HTTP to HTTPS.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L, R=301]
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
For the code to take effect, flush the permalink rules by simply opening the Permalinks admin page.
Changelog
| Since 1.5.0 | Introduced. |
Where the hook is called
mod_rewrite_rules
wp-includes/class-wp-rewrite.php 1605
$rules = apply_filters( 'mod_rewrite_rules', $rules );