Use mod_rewrite to redirect from example.com/dir to www.example.com/dir
Assume /
is the document root of my domain example.com
.
/.htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
/dir/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /dir/index.php [L]
</IfModule>
I know how to redirect example.com/dir
to www.example.com/dir
, because /.htaccess
does the very job.
However, the trick here is that I have to keep /dir/.htaccess
to serve up virtual directories (such as /dir/state/AK/35827/
which aren't actual directories) if you know what I mean.
Problem is, if I keep /dir/.htaccess
, a request of:
http://example.com/dir/state/AK/35827/
DOES NOT redirect to:
http://www.example.com/dir/state开发者_开发知识库/AK/35827/
as would:
http://example.com/
redirect to:
http://www.example.com/
Not sure if I made it clear.
Basically, how to make http://example.com/dir/state/AK/35827/
correctly redirect to http://www.example.com/dir/state/AK/35827/
AND I can serve virtual URLs?
If you do have access to your apache VirtualHosts configuration then you need:
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
This will succesfully redirect http://example.com/ to http://www.example.com/ and http://example.com/dir/state/AK/35827/ to http://www.example.com/dir/state/AK/35827/
The "problem" here is that mod_rewrite does not "inherit" the parent config (.htaccess
) by default. The mod_rewrite directives in the subdirectory completely override the mod_rewrite directives in the parent directory (different to other modules).
You either need to:
Copy the canonical www redirect from the parent
.htaccess
file into/dir/.htaccess
. But code duplication is not desirable.OR: Enable mod_rewrite inheritance in the child
.htaccess
file:RewriteOptions inherit
This effectively "copies" the mod_rewrite directives from the parent
.htaccess
file. However, if you have other directives, this might not work as expected. Note that this "copies" the directives, without changing the directory-prefix.OR: do everything in the parent
.htaccess
file. Having a single.htaccess
file is probably the preferred solution. For example:RewriteEngine on # Canonical redirect RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L] # Virtual directories... RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^dir/ dir/index.php [L]
精彩评论