2

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]
Ankur Tiwari
  • 2,762
  • 2
  • 23
  • 40
Jyoti Sandhiya
  • 173
  • 3
  • 12

4 Answers4

3

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
Ankur Tiwari
  • 2,762
  • 2
  • 23
  • 40
0
RewriteEngine On 
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80 //If you want the condition to match port
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

Try in this. Hope this may help you.

Gaurav Khatri
  • 387
  • 3
  • 11
  • Please add some explanation to these rules - "try this" does not help the OP to learn what you've changed and why this change makes a difference – Nico Haase Feb 13 '19 at 09:41
0

Try this

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
VinothRaja
  • 1,405
  • 10
  • 21
  • Please add some explanation to these rules - "try this" does not help the OP to learn what you've changed and why this change makes a difference – Nico Haase Feb 13 '19 at 09:41
0

APACHE

RewriteCond %{HTTPS} off 
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

NGINX

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /srv/www/example.com/keys/ssl.crt;
    ssl_certificate_key /srv/www/example.com/keys/www.example.com.key;
    return 301 https://www.example.com$request_uri;
}

You can replace ssl on; directive with listen 443 ssl; as recommendation from nginx documentation.

Brn.Rajoriya
  • 1,534
  • 2
  • 23
  • 35