Rewrite to URL outside of Wordpress base Rewrite to URL outside of Wordpress base wordpress wordpress

Rewrite to URL outside of Wordpress base


Adding some rules in your htaccess, while using Wordpress, is always tricky. Instead, you should use its rewrite API.

First, put this code at then end of /wp-content/themes/CURRENT_THEME_ACTIVATED/functions.php:

function my_custom_page_rewrite_rule(){    add_rewrite_rule('^subpage/?', 'index.php?pagename=page/subpage', 'top');}add_filter('init', 'my_custom_page_rewrite_rule');

Remark: you need to specify the page levels in pagename parameter, otherwise the url will change.

Then, you need to tell Wordpress it has to take your new rule into consideration. For this, go to your admin panel: Settings > Permalinks > click on Save button. Now, you should be able to go to domain.com/blog/subpage and see the content of domain.com/blog/page/subpage (the url does not change anymore).

Finally, if you want to make domain.com/subpage reachable, you need to add a htaccess in root folder and put this code into it:

RewriteEngine OnRewriteBase /RewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^([^/]+)/?$ blog/$1 [L]

And... that's it. You can go to domain.com/subpage and now you'll get what you want.