In .htaccess, how to redirect non-lowercase versions of hostname

青春壹個敷衍的年華 提交于 2019-12-24 09:58:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!