Apache mod_rewrite: force www only if not in localhost

前端 未结 3 1938
庸人自扰
庸人自扰 2021-02-02 07:38

I have the following in my htaccess to force the www in URLs:

RewriteCond %{HTTP_HOST} !^www\\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]


        
相关标签:
3条回答
  • 2021-02-02 07:50

    RewriteCond is already your "if-condition". Just add another one:

    RewriteCond %{HTTP_HOST} !=localhost
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    
    0 讨论(0)
  • 2021-02-02 07:59

    I added all these:

    RewriteCond %{HTTP_HOST} !=localhost
    RewriteCond %{HTTP_HOST} !=127.0.0.1
    RewriteCond %{REMOTE_ADDR} !=127.0.0.1
    RewriteCond %{REMOTE_ADDR} !=::1
    
    0 讨论(0)
  • 2021-02-02 08:06

    If you're using a port other than 80 (e.g. localhost:8080) you might need to add it to the regex too:

    RewriteCond %{HTTP_HOST} !^localhost(?::\d+)?$ [NC]
    RewriteCond %{HTTP_HOST} !^127\.0\.0\.1(?::\d+)?$
    
    0 讨论(0)
提交回复
热议问题