I am developing a WordPress plugin that modifies the standard WordPress .htaccess file on the webroot folder. Currently, I inject my code inside the # BEGIN WordPress block, like so:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# BEGIN This is my block
RewriteCond %{REQUEST_URI} \.(css|js)$
RewriteRule . index.php [L]
# END This is my block

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Is this a best practice? Or should I create a new <IfModule mod_rewrite.c> block for this code?

Also, is there anything else I should take note of when creating plugins that modify .htaccess?

P.S. I am adding this .htaccess block because I want to modify some parts of .css and .js files with PHP before I output them.


You certainly should not be modifying the # BEGIN WordPress block, as this is likely to be overridden by WordPress itself.

You should create a new section before the WordPress front-controller. This will work just as well and keep the directives separate.

There is no need to use a <IfModule mod_rewrite.c> wrapper, in fact you should not use a wrapper in this instance, since your plugin would seem to be dependent on mod_rewrite being enabled. Your plugin will not function correctly if mod_rewrite is not available, so you shouldn't "fail silently" if it isn't.

Aside: There is also no need to repeat the RewriteEngine and RewriteBase directives. If you are hand-coding the .htaccess file then you would not duplicate them. However, if you are injecting this code programmatically, then you probably need to - to be sure. (Multiple RewriteEngine and RewriteBase directives are not strictly supported. The last instance in any given context wins and controls the entire file. For example, if you place RewriteEngine Off as the very last directive in the .htaccess file then it is Off for the entire file, despite there being earlier RewriteEngine On directives.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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