WordPress: Prevent WP from Overwriting Custom htaccess Rules

If you need to use custom Mod re-write rules – .htaccess rules – in a WordPress blog, you have a couple of options.  You could use WordPress’ built-in rewriting engine.  I have created a plugin that facilitates that and makes it pretty easy.  You can get the plugin here.  If, however, your app needs to bypass the WordPress app, you will need to put your rewrite rules directly in the .htaccess file.  The trouble is that if you’re using pretty urls for permalinks in WordPress, it has the horrible habit of rewriting portions of that file and you lose your rules if you don’t do it properly.  This seems happen at odd times like creating or updating a Page or a Post.

Preventing WP from Overwriting your Rewriting: Solution

Thanks to Richard at Red Cardinal for pointing out the very simple fix to this problem here.

The fix is simple:

Don’t put your rules in the WordPress block: # BEGIN WordPress……… # END WordPress

Here’s a sample from my SugarDo.com application that has to use the .htaccess rewriting option:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^lists/(.*)/(.*)/$ sug_lists.php?list_id=$1&item_id=$2 [L]
RewriteRule ^lists/(.*)/(.*)$ sug_lists.php?list_id=$1&item_id=$2 [L]
RewriteRule ^lists/(.*)/$ sug_lists.php?list_id=$1 [L]
RewriteRule ^lists/(.*)$ sug_lists.php?list_id=$1 [L]
RewriteRule ^lists/$ sug_lists.php [L]
RewriteRule ^lists$ sug_lists.php [L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

As the RIchard notes in his article, you will wind up with the “RewriteEngine On” section twice since WordPress will add that in the # BEGIN WordPress block.  And you have to have it at the top for your rules to work.  But it doesn’t seem to hurt anything.

Thanks Richard!



One Response to WordPress: Prevent WP from Overwriting Custom htaccess Rules

  1. mikeyb October 18, 2010 at 2:56 am #

    Sorry for necroreplying, but this is awesome, thank you so much. I’m currently redesigning my site in WordPress, and this is totally going to come in handy if the rewriting engine is still causing problems

Powered by WordPress. Designed by Woo Themes