Add rewrite rule in plugin: with .htaccess in plugin folder or using WordPress functions

I need add a rewrite rule in my plugin, and distribute it with my code. All works fine if I put the rule in the .htaccess in the WordPress root folder, but I need distribute the plugin with my rule.

I try to put a .htaccess inside the plugin folder and try to use the add_rewrite_rule function but doesn’t works either.

Here the .htaccess code that works correctly in WordPress root folder but doesn’t works in my plugin folder:

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteRule my-plugin/pages/tp(.*)\.php$ wp-content/plugins/my-plugin/pages/request.php?pid=$1

</IfModule>

I try the follow code in my plugin but doesn’t works either:

add_filter( 'query_vars', 'add_query_vars' );
function add_query_vars( $query_vars )
{
    $query_vars[] = 'pid';
    return $query_vars;
}
add_action( 'init', 'add_init' );
function add_init()
{
    $plugin_url = 'the-path-to-my-plugin-folder';
    add_rewrite_rule('my-plugin/pages/tp(.*)\.php'
                  , $plugin_url . 'pages/request.php?pid=$matches[1]','top');

    global $wp_rewrite;
    $wp_rewrite->flush_rewrite_rules(); // I know this should be called only one time, but I put it here just to keep simple the sample code
}

But I always get the error that the URL wasn’t found.
What I’m doing wrong? How can I do what I need? I searched for similar questions but none solve my problem.

Solutions Collecting From Web of "Add rewrite rule in plugin: with .htaccess in plugin folder or using WordPress functions"

NOTE: WordPress Rewrite API is not the same as Apache Rewrite module.
WP Rewrite API doesn’t redirect a request to another URL, it used to
parse current URL and fill query_vars array.

The issue is in the second parameter of you add_rewrite_rule function call. It has to start from index.php? and then there should be your arguments, like pid, for example:

"index.php?pid=$matches[1]...."

So your add_init function should be like this:

add_action( 'init', 'wpse8170_add_init' );
function wpse8170_add_init()
{
    add_rewrite_rule('my-plugin/pages/tp(.*)\.php', 'index.php?pid=$matches[1]', 'top');
}

Don’t forget to flush rewrite rules by visiting Settings » Permalinks page.

Further reading:

  • The Rewrite API: The Basics
  • The Rewrite API: Post Types & Taxonomies