mod_rewrite - add www

前端 未结 3 1618
半阙折子戏
半阙折子戏 2021-01-02 05:03

I\'m trying to force www for my site address with .htaccess:

RewriteCond %{HTTP_HOST} ^mysite\\.com$ [NC]
RewriteRule ^(.*)$ http:/         


        
相关标签:
3条回答
  • 2021-01-02 05:41

    The problem is right here:

    RewriteCond %{HTTP_HOST} ^mysite\.com$ [NC]
    

    ^ specifies the beginning of the string while $ specifies the end.

    In order to make it work you need to have a wildcard select after the .com or .+.

    to reiterate what Alex said:

     <IfModule mod_rewrite.c>
       RewriteCond %{HTTPS} !=on
       RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
       RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
     </IfModule>
    
    0 讨论(0)
  • 2021-01-02 05:47

    From the superb HTML5 Boilerplate .htaccess:

    <IfModule mod_rewrite.c>
      RewriteCond %{HTTPS} !=on
      RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
      RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    </IfModule>
    
    0 讨论(0)
  • 2021-01-02 05:49

    Actually, I have to disagree with Mr. Szanto.

    It would appear the problem was not with the:

    RewriteCond %{HTTP_HOST} ^mysite\.com$ [NC]
    

    Through some additional research (via Google) I found that this worked great for me:

    <IfModule mod_rewrite.c>
      RewriteCond %{HTTPS} !=on
      RewriteCond %{HTTP_HOST} ^mysite\.com$ [NC]
      RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    </IfModule>
    

    Mr. Szanto's answer, while well formatted, seems to redirect all requests missing the 'www' to be redirected with the 'www' attached. This was not a desirable outcome with most subdomains. The above code only redirects if there is no 'www' AND no subdomain before the TL domain name.

    Hope this helps others.

    0 讨论(0)
提交回复
热议问题