How to force https and www. in .htaccess?

by cameron_walter , in category: SEO , 6 months ago

How to force https and www. in .htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by jaycee_rowe , 6 months ago

@cameron_walter 

To force HTTPS and www. in .htaccess, you can use the following code:

1
2
3
4
5
6
7
8
9
RewriteEngine On

# Force HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Force www
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


This code uses Apache's mod_rewrite module to perform URL rewriting. Here's a breakdown of what each line does:

  1. RewriteEngine On: Enables the rewriting engine for this .htaccess file.
  2. RewriteCond %{HTTPS} !=on: Checks if HTTPS is not already on.
  3. RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]: Redirects the request to the HTTPS version of the current URL using a 301 (permanent) redirect. %{HTTP_HOST} captures the current domain. %{REQUEST_URI} captures the path and query string of the request. L flag indicates that no further rewriting rules should be processed. R=301 flag specifies a 301 redirect.
  4. RewriteCond %{HTTP_HOST} !^www.: Checks if the domain does not start with "www.".
  5. RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]: Redirects the request to the "www." version of the current URL using a 301 redirect. This rule is only applied if HTTPS is already enabled since it comes after the previous rule. %{HTTP_HOST} captures the current domain. %{REQUEST_URI} captures the path and query string of the request. L flag indicates that no further rewriting rules should be processed. R=301 flag specifies a 301 redirect.


Make sure to place this code in the .htaccess file located in the root directory of your website.