How do I redirect a request for a specific URL to the domain root using htaccess?
The short answer
RedirectMatch 301 ^/the-url-to-redirect/$ http://www.domain.tld/the-new-url/
The Problem
I have a WordPress blog in a subdirectory, but I want calls for the domain root to display content of the sub directory. However I also want the sub directory to display in the URL for all OTHER URL requests. Eg http://www.domain.tld/blog/page-url
Note:
WordPress has a built in mechanism to allow the blog to be installed in a sub directory but REMOVES THE SUB DIRECTORY FROM THE URL. See:
http://codex.wordpress.org/Giving_WordPress_Its_Own_Directory
The Solution
Follow the instruction in the above URL the above, COPY (not move) to domain root the WordPress index.php file but change the line:
require(‘./wp-blog-header.php’);
to
require(‘./blog/wp-blog-header.php’);
But keep the settings:
WordPress Address (URL) http://www.domain.tld/blog/
Site Address (URL) http://www.domain.tld/blog/
And leave the sub directory htaccess file where it is
Problem 2
I now have a Duplicate Content issue with:
http://www.domain.tld and http://www.domain.tld/blog/
To solve this I can create a 301 permanent redirect for the sub directory (top of this page).
Problem 3
WordPress 2.9 onwards will automatically create canonical URLs in the header of every page. This is a useful addition, but in this case the page at http://www.domain.tld/blog/ carries the canonical tag for http://www.domain.tld/blog/ but that page now redirects to http://www.domain.tld/ creating a permananet loop between the canonocal link and the RedirectMatch 301. Is it a problem? Who knows but I would rather not risk losing my SEO juice over it by having a permanent loop
We can remove the automatically generated canonical links by placing the following in the themes functions.php file
# Remove WordPress canonical links
remove_action(‘wp_head’, ‘rel_canonical’);
But I don’t want to turn off ALL my canonical link tags, only the one on the sub directory, therefore I use this in the themes functions.php instead:
# Remove WordPress canonical from front_page
add_action(‘template_redirect’, ‘my_canonical’);
function my_canonical()
{
if(is_front_page())
{
remove_action( ‘wp_head’, ‘rel_canonical’ );
}
}
See: http://stackoverflow.com/questions/2202829/wordpress-init-remove-action-with-conditional-tags
Now we have:
http://www.domain.tld/ for the front page
http://www.domain.tld/blog/ no longer exists alone (it redirects to root)
http://www.domain.tld/blog/full-page-urls for all other pages
All pages carry:
<link rel=’canonical’ href=’http://www.domain.tld/blog/full-url-here’ />
Apart from: http://www.domain.tld/ which we can deal with separately for duplicate content issues.