Search code examples
.htaccesssslhttp-redirecthttpsserver

Redirect http to https with www using .htaccess


How can I redirect HTTP to https include WWW using .htaccess?

Example :

  1. redirect http://example.com to https://www.example.com
  2. redirect http://www.example.com to https://www.example.com
  3. redirect https://example.com to https://www.example.com

I'm trying

RewriteEngine On

RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' [OR]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,R=301,L]

RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,R=301,L]

Solution

  • You can put the following code inside your .htaccess file

    RewriteEngine On
    # ensure www.
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # ensure https
    RewriteCond %{HTTP:X-Forwarded-Proto} !https 
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    

    This .htaccess file will redirect http://example.com/ to https://example.com/.

    Code Explanation:

    • [NC] matches both upper and lower case versions of the URL
    • The X-Forwarded-Proto (XFP) header is a de-facto standard header for identifying the protocol