.htaccess Redirect Codes

Redirect http to https using .htaccess in Apache

As per Google recommendation, it is good to secure your website with an SSL Certificate. It not only creates trust for users but also serves as a primary SEO factor.

Once you implemented SSL, you may want to redirect all web traffic from ‘http’ to ‘https’ using a .htaccess configuration file in the Apache web server.


Code to redirect all links from ‘http’ to ‘https’:

You can create a new '.htaccess' file if it is not there in the website root. 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.

<IfModule mod_rewrite.c>
RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]
</IfModule>

Explanation:
<IfModule> is Apache directive that check if mod_rewrite module is loaded.
RewriteEngine OnEnables runtime rewriting engine.
RewriteCond %{SERVER_PORT} 80 restrict the rewrites to requests on port 80./li>
RewriteRule creates a rule to rewrite one URL to another.
[R=301,L] – Here, R=301 force 301 (permanent) redirects.
[R=301,L] – Here, L means “last rule” to stop further rules processing if this rule matched.

SEO Recommends 301:
If you are permanently redirecting URLs, you should use 301 redirects to maintain SEO, else 302 can be used for temporary URL redirects.

Note: Note: If redirection code does not work, try placing code in the beginning of .htaccess file.