htaccess redirect to https://www

QuestionsCategory: Questionshtaccess redirect to https://www
Jack asked 3 months ago

I have the following htaccess code:

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteCond !{HTTPS} off
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


I want my site to be redirected to https://www. with HTTPS, and enforcing the www. subdomain, but when I access http://www. (without HTTPS), it does not redirect me to https://www with HTTPS.

1 Answers
Raymond John Staff answered 3 months ago

To first force HTTPS, you must check the correct environment variable %{HTTPS} off, but your rule above then prepends the www. Since you have a second rule to enforce www., don’t use it in the first rule.

Start your code here
RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

But also for more redirect rules, see this : 
A collection of useful .htaccess snippets
Force www

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

Force non-ww
RewriteEngine on RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] RewriteRule ^(.*)$$1 [L,R=301]

Block Visitors by Referrer

Start your code here
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]

For more redirect rules, visit