问题
I am utilizing other mod_rewrite conditions in my .htaccess file and also want to ensure that my domain is always prefixed with www (for session storing and seo). However with my current .htaccess if I go to example.com it works great, but if I go to example.com/folder it will redirect to www.example.com (leaving out /folder) Is there something I'm doing wrong here?
my .htaccess file
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
# Rules for: actions
RewriteRule ^([-_!~*'()$a-zA-Z0-9]+)/?$ ./date/index.php?action=$1 [L,QSA]
回答1:
The rewrite engine is multi-pass. It loops picking the lowest .htaccess file on the path with RewriteEngine On until no further rewrite changes occur. So for this example.com/folder/xxx request -- if an .htaccess file exists in DOCROOT/folder then it will be used and the rewrite rules in DOCROOT/.htaccess will be ignored.
You can use a single .htaccess in DOCROOT or a hierarchy. The single DOCROOT .htaccess file has a small performance advantage as the engine only needs to open and to read in a single .htaccess file. I describe this in more detail in this article, More on using Rewrite rules in .htaccess files
You are not specifying a RewriteBase and so the engine can often lose directories as here in your case. So I would use the following in DOCROOT/.htaccess:
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} =example.com
RewriteRule ^.* http://www.example.com/$0 [R=301,L]
where DOCROOT is your Apache document root directory.
I am also curious about your inclusion character set for the date pattern. Seems odd to me, but leaving this aside, it's better written as
RewriteRule ^([-_!~*'()$\w]+)/?$ date/index.php?action=$1 [L,QSA]
assuming, of course, that you want to activate DOCROOT/date/index.php
来源:https://stackoverflow.com/questions/9224462/mod-rewrite-force-www-prefix-selectively-working