WebMasterCampus
WEB DEVELOPER Resources

Redirect Http to Https Using Htaccess

Redirect Http to Https Using Htaccess | htaccess redirect to https://www


Always make sure your website follows Google recommendation, and as per recommendation secure your website with an SSL Certificate. It fulfils two major benefits, first it serves as a primary SEO factor for search engines and second creates trust for website users.

After configuration of SSL from cpanel or hosting configuration, you need to redirect all web traffic from ‘http’ to ‘https’. You can easily achieve that using a .htaccess configuration file in the Apache web server domain folder.

  • You can create a new ‘.htaccess’ file if it is not there in the website root domain folder.
  • If it is already there, you need to put the following code in ‘.htaccess’ file.
  • If it does not work with the existing code, you can try placing it in the beginning of the existing code.

Note: replace your-website-url.com with your own website name on both locations

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteCond %{HTTP_HOST} ^your-website-url.com$ [NC]
    RewriteRule ^(.*)$ https://www.your-website-url.com/$1 [L,R=301]
</IfModule>

RewriteCond %{HTTP_HOST} The HTTP_HOST server variable contains the value of the Host HTTP request header (ie. the hostname), this is irrespective of the protocol used (HTTP or HTTPS).

So, based on RewriteCond says true means condition match then will be redirect rule will according to RewriteRule.

Note: replace your-website-url.com with your own website name on both locations

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^your-website-url.com [NC]
    RewriteRule ^(.*)$ https://www.your-website-url.com/$1 [L,R=301]
</IfModule>

RewriteCond %{HTTP_HOST} The HTTP_HOST server variable contains the value of the Host HTTP request header (ie. the hostname), this is irrespective of the protocol used (HTTP or HTTPS). If Yes then will be redirect rule will redirect to port 443 https.

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{SERVER_PORT} 80
    RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
</IfModule>

RewriteCond %{SERVER_PORT} 80 check the request for web page or resource coming through port 80. If Yes then will be redirect rule will redirect to https.

[R=301,L] – Here, L means “last rule” to stop further rules processing if this rule matched.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} !on
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</IfModule>
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
Created with love and passion.