Redirect non-www to www in .htaccess

后端 未结 13 1971
轻奢々
轻奢々 2020-11-22 05:51

I have this in my .htaccess file:

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

but whenever I

13条回答
  •  天涯浪人
    2020-11-22 06:27

    If possible, add this to the main Apache configuration file. It is a lighter-weight solution, less processing required.

    
            ServerName example.com
            Redirect permanent / http://www.example.com/
    
    
       ServerAdmin me@example.com
       ServerName www.example.com
       DocumentRoot /var/www/example
       .
       .
       . etc
    

    So, the separate VirtualHost for "example.com" captures those requests and then permanently redirects them to your main VirtualHost. So there's no REGEX parsing with every request, and your client browsers will cache the redirect so they'll never (or rarely) request the "wrong" url again, saving you on server load.

    Note, the trailing slash in Redirect permanent / http://www.example.com/. Without it, a redirect from example.com/asdf would redirect to http://www.example.comasdf instead of http://www.example.com/asdf.

提交回复
热议问题