skip to Main Content

I want to redirect my domain http to https and I have already do that with below mention code

RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain.com [NC]
RewriteRule ^(.*)$ https www.domain.com/$1 [L,R=301,NC]

When a user enter domain.com it’s automatically redirect to https www.domain.com But when user enter only www.domain.com it’s redirect to the http www.domain.com

Please help me to solve this issue.

2

Answers


  1. You can use:

    RewriteEngine on
    # Test without www
    RewriteCond %{HTTP_HOST} !^www. [OR,NC]
    # Test for http
    RewriteCond %{HTTPS} off 
    # Redirect to https www
    RewriteRule ^ https://www.exemple.com%{REQUEST_URI} [NE,R=301,L]
    
    Login or Signup to reply.
  2. At your code :

    RewriteCond %{HTTP_HOST} ^domain.com [NC]
    

    It is a condition for the following rule ; so the rule will be applied only for none www request.

    Moreover , don’t use R=301 redirection when you test new code unless you make sure that your rules is ok and you could use R=302 or just R.

    regardless of your code Put the following code at your main directory .htaccess :

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]
    

    If you want to force every request to be www you should do this :

    RewriteEngine On
    
    RewriteCond %{HTTPS} !=on
    #this line above will match any request without `https`
    
    RewriteCond %{HTTP_HOST} ^www. [NC]
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]
    
    #the two lines above will exclude none `www` request and force only `www` request unto `https` and the rule will stop here `L`
    
    RewriteCond %{HTTP_HOST} !^www. [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R]
    
    # the last two line will exclude any `www` request and force only none `www` into `https`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search