问题
Until now I have used this code to redirect request from example.com/url/to/page to www.example.com/url/to/page
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Recently I added shortlinks like example.com/x/abc to my page These links should not have "www" at the beginning
I tried
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} !^x/ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
but this does not work. Firebug shows 2 redirects: non-www to www and then shortlink to longlink instead of just 1 redirect shortlink to longlink. I also empty cache each time I change .htaccess
How can I achieve the correct redirection?
回答1:
This should work:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} !^/x/ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
%{REQUEST_URI}
starts matching from a slash at the start.
来源:https://stackoverflow.com/questions/18814335/htaccess-force-www-except-subfolder