How to redirect non-www to www URL's using htaccess?

前端 未结 4 1741
暗喜
暗喜 2020-11-29 01:38

I have a website say http://www.example.com/ in the root of my website, I have added .htaccess file to redirect any request of http://example.com/ to http://www.example.com/

相关标签:
4条回答
  • 2020-11-29 02:10

    This is Best Solutions to redirect non-www to www URL's using htaccess. using this code in htaccess file and check url.

    Options +FollowSymlinks
    RewriteEngine on
    rewritecond %{http_host} ^mydomain.com [nc]
    rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]
    
    0 讨论(0)
  • 2020-11-29 02:24

    I think it may just be that your existing rule is too strict, and is not getting triggered in your subdirectory because of this. Something like this should work site-wide:

    RewriteEngine on
    RewriteBase /
    
    RewriteCond %{HTTP_HOST} ^example\.com$
    RewriteRule ^(.*) http://www.example.com/$1 [R=301]
    
    0 讨论(0)
  • 2020-11-29 02:25

    This is a more generic solution, because it can be used with any domain name without having to specify the specific domain name in each .htaccess:

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

    The contrary is also possible (www to non-www):

    # Redirect www to non-www
    RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
    
    0 讨论(0)
  • 2020-11-29 02:29

    I recommend everyone to stick with the below method it will only redirect the main domain only not any other sub-directory or sub-domain in your host.

    # Redirect non-www to www only for main domain 
    # recommended if you have any/some sub-domain(s)
    RewriteEngine on
    RewriteBase /
    
    # Replace yoursite and .tld respectively
    RewriteCond %{HTTP_HOST} ^yoursite\.tld$
    # Replace yoursite.com
    RewriteRule ^(.*) http://www.yoursite.com/$1 [R=301]
    

    Use this method if you are really sure and I hope you will that you won't ever use sub-domain with your website i.e. subdomain.yoursite.com or whatever. Than you're welcome to use the below method. "Saying Again make sure if you really want to use this method"

    # Redirect all non-www to www including subdomain(s)
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    

    The below method will redirect all www url to non-www including your sub-domains although you cannot use www.subdirecty.yoursite.com it will prompt you an error with 500.

    # Redirect www to non-www
    RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
    
    0 讨论(0)
提交回复
热议问题