WordPress Mod_Rewrite Injecting Server Path

This is a problem that those running WordPress in a subdirectory on an Apache web server may find when using mod_rewrite to try to avoid duplicate content issues.

To illustrate the problem, let's say that you have your WordPress files installed in a subdirectory named "blog" and within that subdirectory, you have an .htaccess file that contains something like:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule (.*) http://www.example.com/blog/$1 [R=301,L]
</IfModule>

What you want to happen is to have someone be able to type in http://example.com/blog or http://example.com/blog/ and have that request automatically redirected to http://www.example.com/blog/

What happens instead though is that when someone types in http://example.com/blog
the server adds your server root path to "blog" to the end of the URL and, as a result, may also display a 404 "File Not Found" error. The URL ends up looking something like:
http://www.example.com/blog//my/server/path/to/blog
instead of just http://www.example.com/blog/ as you intended to happen.

When typing http://example.com/blog (without the trailing slash), Apache thinks it should be looking for a file named blog.

Caution: Mod_rewrite is an extremely powerful tool. Whenever using mod_rewrite, test thoroughly and use with care. No warranty of code is expressed or provided. Use at your own risk.

The solution for this is actually a very easy one. Just remove the $1 from the RewriteRule, i.e. change:
RewriteRule (.*) http://www.example.com/blog/$1 [R=301,L]
to
RewriteRule (.*) http://www.example.com/blog/ [R=301,L]

That should do it.

Caution: Mod_rewrite is an extremely powerful tool. Whenever using mod_rewrite, test thoroughly and use with care. No warranty of code is expressed or provided. Use at your own risk.



 
Google Search