I’m writing a small plugin that needs to write to .htaccess a simple non_wp_rule and i am doing it like this:

function ci_flush_rules()
{
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}
register_activation_hook(__FILE__, 'ci_flush_rules');


function ci_add_rules()
{
    global $wp_rewrite;
    $proxy = plugin_dir_path(__FILE__) . 'proxy.php';
    $non_wp_rules = array('(.*)\.(jpe?g|gif|png)$' => $proxy);
    $wp_rewrite->non_wp_rules = $non_wp_rules + $wp_rewrite->non_wp_rules;
}
add_action('generate_rewrite_rules', 'ci_add_rules');

The rule is written in the .htaccess file as expected.

Now i have 2 problems.

Problem 1

When i try to remove this rule during plugin deactivation like this:

function ci_remove_rules()
{
    global $wp_rewrite;
    $wp_rewrite->non_wp_rules = array();
    $wp_rewrite->flush_rules();

} 
register_deactivation_hook( __FILE__, 'ci_remove_rules' );

The rule doesn’t get removed. If i deactivate the plugin and then visit Settings > Permalinks it removes the rule.

Problem 2

WordPress is installed in a subdirectory ( http://localhost/wordpress ) and when the rule is written in the .htaccess it appears like that:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteRule ^(.*)\.(jpe?g|gif|png)$ /wordpress/Applications/MAMP/htdocs/wordpress/wp-content/plugins/myplugin/proxy.php [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>
# END WordPress

As you can see instead of a path like /Applications/MAMP…. it’s /wordpress/Applications/MAMP….

Bare with me as this is the first time dealing with wp_rewrite stuff 🙂

1 Answer
1

Problem 1

Your hook ci_add_rules() will still run when you flush rules, so remove it first (and avoid “unsetting” non_wp_rules, you’ll break other plugins that make use of it).

function ci_remove_rules()
{
    remove_action( 'generate_rewrite_rules', 'ci_add_rules' );
    $GLOBALS['wp_rewrite']->flush_rules();
}

Problem 2

Pretty sure you want:

plugin_dir_url( 'proxy.php', __FILE__ )

..instead of:

plugin_dir_path( __FILE__ ) . 'proxy.php

Leave a Reply

Your email address will not be published. Required fields are marked *