问题
In .htaccess
on Apache2, how do you redirect all capitalization variations of a hostname to a canonical lowercase version, via 301 redirect, and keeping the rest of the path unharmed. Subdomains (or not) should do the same as well.
Additionally, accessing via an IP should not redirect.
examples:
http://Example.com/foo
=>http://example.com/foo
http://A.example.com/foo
=>http://a.example.com/foo
http://A.EXample.com/foo?bar
=>http://a.example.com/foo?bar
http://208.67.222.222/foo
=>http://208.67.222.222/foo
回答1:
# Make sure hostname is lowercase only (or an IP address)
RewriteCond %{HTTP_HOST} !^(.+\.)?example\.com$
RewriteCond %{HTTP_HOST} !^[\d\.]{7,15}$
RewriteRule ^(.*)$ ${lowercase:%{HTTP_HOST}}/$1 [R=301,L]
回答2:
I've searched and been unable to find a solution online that encompasses any number of domains. The use-case for me is that I work on localhost, and so the first line (with example.com) will not work on both localhost and my domain, and any other name someone uses instead of localhost.
To add to @philfreo 's answer, therefore: (copying the lines but modifying only the first one)
# Make sure hostname is lowercase only (or an IP address)
RewriteCond %{HTTP_HOST} !^(.+\.)?(.+)?$
RewriteCond %{HTTP_HOST} !^[\d\.]{7,15}$
RewriteRule ^(.*)$ ${lowercase:%{HTTP_HOST}}/$1 [R=301,L]
Props to philfreo! Much time saved with his response.
Paragon
来源:https://stackoverflow.com/questions/4161059/in-htaccess-how-to-redirect-non-lowercase-versions-of-hostname