apache redirect from non www to www

前端 未结 24 949
春和景丽
春和景丽 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 07:08

    Redirection code for both non-www => www and opposite www => non-www. No hardcoding domains and schemes in .htaccess file. So origin domain and http/https version will be preserved.

    APACHE 2.4 AND NEWER

    NON-WWW => WWW:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ %{REQUEST_SCHEME}://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    

    WWW => NON-WWW:

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

    Note: not working on Apache 2.2 where %{REQUEST_SCHEME} is not available. For compatibility with Apache 2.2 use code below or replace %{REQUEST_SCHEME} with fixed http/https.


    APACHE 2.2 AND NEWER

    NON-WWW => WWW:

    RewriteEngine On
    
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    

    ... or shorter version ...

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS}s ^on(s)|offs
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    

    WWW => NON-WWW:

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

    ... shorter version not possible because %N is available only from last RewriteCond ...

提交回复
热议问题