Hack: Redirects Without htaccess

If you are one of those developers that loves playing with htaccess you know you can do all sorts of redirects there. But not everyone can edit that file. And even if you can, there is something to be said for leaving it alone and including all of your customizations in your own plugin or functions.php file.

By using add_rewrite_rule during the init action you can insert rewrites that look just like the ones in htaccess. Here is a simple and direct one, but you can get all fancy with regular expressions too.

add_action( 'init', 'wpaction_rewrite_rules' );
function wpaction_rewrite_rules() {
    add_rewrite_rule('testing', 'index.php?pagename=tarantula-nebula', 'top');
}

You can just keep adding more calls to add_rewrite_rule if you like. But you can also get clever with some PHP code if you think about it. You can’t do that in htaccess. That brings up all sorts of possibilities.

Now if you try this, you’ll find it doesn’t work. Why not? Well, there is one little step left. You need to clear out and regenerate the rewrite rules in the admin. Search and you will not find this function. It is hidden. Just go to Settings, Permalink. Then, without making any changes, just click the Save button on that page. Then your new redirect will work.

Leave a Reply

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