apache redirect from non www to www

前端 未结 24 936
春和景丽
春和景丽 2020-11-22 06:34

I have a website that doesn\'t seem to redirect from non-www to www.

My Apache configuration is as follows:

RewriteEngine On
### re-direct t         


        
相关标签:
24条回答
  • 2020-11-22 06:52

    To remove www from your URL website use this code in your .htaccess file:

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

    To force www in your website URL use this code on .htaccess

    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} ^YourSite.com$
    RewriteRule ^(.*)$ http://www.yourSite.com/$1 [R=301]
    RewriteCond %{REQUEST_fileNAME} !-d
    RewriteCond %{REQUEST_fileNAME} !-f
    RewriteRule ^(([^/]+/)*[^./]+)$ /$1.html [R=301,L]
    

    Where YourSite.com must be replaced with your URL.

    0 讨论(0)
  • 2020-11-22 06:52

    This is similar to many of the other suggestions with a couple enhancements:

    • No need to hardcode the domain (works with vhosts that accept multiple domains or between environments)
    • Preserves the scheme (http/https) and ignores the effects of previous %{REQUEST_URI} rules.
    • The path portion not affected by previous RewriteRules like %{REQUEST_URI} is.

      RewriteCond %{HTTP_HOST} !^www\. [NC]
      RewriteRule ^(.*)$ %{REQUEST_SCHEME}://www.%{HTTP_HOST}/$1 [R=301,L]
      
    0 讨论(0)
  • 2020-11-22 06:54

    Try this:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^example.com$ [NC]
    RewriteRule ^(.*) http://www.example.com$1 [R=301]
    
    0 讨论(0)
  • 2020-11-22 06:55

    I found it easier (and more usefull) to use ServerAlias when using multiple vhosts.

    <VirtualHost x.x.x.x:80>
        ServerName www.example.com
        ServerAlias example.com
        ....
    </VirtualHost>
    

    This also works with https vhosts.

    0 讨论(0)
  • 2020-11-22 06:56
    <VirtualHost *:80>
        ServerAlias example.com
        RedirectMatch permanent ^/(.*) http://www.example.com/$1
    </VirtualHost>
    
    0 讨论(0)
  • 2020-11-22 06:59
    RewriteCond %{HTTP_HOST} ^!example.com$ [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
    

    This starts with the HTTP_HOST variable, which contains just the domain name portion of the incoming URL (example.com). Assuming the domain name does not contain a www. and matches your domain name exactly, then the RewriteRule comes into play. The pattern ^(.*)$ will match everything in the REQUEST_URI, which is the resource requested in the HTTP request (foo/blah/index.html). It stores this in a back reference, which is then used to rewrite the URL with the new domain name (one that starts with www).

    [NC] indicates case-insensitive pattern matching, [R=301] indicates an external redirect using code 301 (resource moved permanently), and [L] stops all further rewriting, and redirects immediately.

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