Wednesday, April 13, 2016

Rewrite to URL outside of Wordpress base

Leave a Comment

My wordpress blog is installed at domain.com/blog and I have a page with subpages whose structure look like domain.com/blog/page and domain.com/blog/page/subpage.

I want my visitors to be able to go to domain.com/subpage and see the content of domain.com/blog/page/subpage without being redirected to that URL externally, avoiding wordpress permalink rewrites.

I tried using RewriteRule ^subpage$ /page/subpage [L] and the content is being served, but the url looks like domain.com/blog/page/subpage (I'd guess Wordpress permalinks are getting to it.)

.htaccess:

# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L]  // tried inserting my code here.  RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] </IfModule>  # END WordPress 

EDIT:

These logs show the activity on page visit -

ip - - [19/Jun/2012:14:03:53 -0400] "GET /subpage/ HTTP/1.1" 301 - "http://domain.com/referrer/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0.1" ip - - [19/Jun/2012:14:03:53 -0400] "GET /blog/page/subpage/ HTTP/1.1" 200 20022 "http://domain.com/referrer/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0.1" 

Also, here is my root .htaccess -

<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog/ RewriteRule ^subpage/?$ /blog/page/subpage/ [QSA,L]  RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] </IfModule>  RewriteCond %{HTTP_HOST} ^domain.com$ [OR] RewriteCond %{HTTP_HOST} ^www.domain.com$ 

1 Answers

Answers 1

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 On RewriteBase /  RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)/?$ blog/$1 [L] 

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

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment