How to redirect Query Strings with ISAPI Rewrite?
I'm using the following lines in my httpd.ini file to redirect users who access example.com to www.example.com:
RewriteCond Host: (?:www\.)?example.com
RewriteRule (.*) http\://www.example.com [RP,L]
I'd like to know how r开发者_如何转开发edirect Query Strings whether user access my site without www, for example:
my user access:
example.com?a=1&b=2
example.com/a/b
i'd like to redirect to:
www.example.com?a=1&b=2
www.example.com/a/b
Someone can help me, please?
Thanks a lot.
This looks like you're using isapi_rewrite v2, so I'll answer for that version. v3 syntax is slightly different.
In the first line, I think it needs a !
for a negative lookahead for the www. As shown, it's matching www instead of not-www.
The answer involves capturing the pieces of the url, then using them in the rewrite with the submatch $1, $2, etc.
RewriteCond Host: (?!www\.)example.com
RewriteRule (.*) http\://www.example.com$1 [I,RP]
You can make it more generic for any domain, just to copy it easily to other websites, by capturing instead of example.com. It becomes the first capture $1, while the rest of the url is now $2.
RewriteCond Host: (?!www\.)(.*)
RewriteRule (.*) http\://www.$1$2 [I,RP]
The rule above will always redirect to http, even if the page was https. If you want to keep http or https, as-is, e.g., https://example.com/a?b=1
to https://www.example.com/a?b=1
, then look for https flag, and substitute the "s". This is tricky to describe in words: this looks for the HTTPS server variable value 'on', and keeps it if it's 'on' (this is now the 2nd capture), and doesn't keep it if it's anything else. Then, in the rule, the ?2 is testing if there is a second capture. If so, it adds an 's', otherwise (the colon), it adds nothing (nothing after the colon). In this set, the rest of the url is now the third substring.
RewriteCond Host: (?!www\.)(.*)
RewriteCond %HTTPS (on)|.*
RewriteRule (.*) http(?2s:)\://www.$1$3 [I,RP]
Finally (almost done!), this doesn't leave subdomains alone. Because of the (.*) instead of 'example.com', it will rewrite abc.example.com/whatever...
to www.abc.example.com/whatever...
. So if you have subdomains to leave alone, e.g., staging or localhost for developers, or say 'shop' for a hosted shopping domain, you can 'or' these with the 'www' (note localhost doesn't have a trailing dot, to handle just //localhost).
RewriteCond Host: (?!www\.|staging\.|shop\.|localhost)(.*)
RewriteCond %HTTPS (on)|.*
RewriteRule (.*) http(?2s:)\://www.$1$3 [I,RP]
精彩评论