mwieczorek
mwieczorek

Reputation: 2252

Forcing HTTPS with subdomains in .htaccess or httpd.conf

I've been unable to get the flow of rewrites in the correct order to force HTTPS and redirect to the 'www' domain by default.

What I'm trying to do is force the 'www' domain if none is provided and at the same time, force to HTTPS, while taking into consideration there are two other subdomains that HTTPS is required for as well.

Scenarios:

http://[domain.com]/* -> https://www.[domain.com]/*
http://assets.[domain.com]/* -> https://assets.[domain.com]/*
http://payloads.[domain.com]/* -> https://payloads.[domain.com]/*

As I understand, this first block check if HTTPS is not on AND if there is no subdomain present, then will redirect to https://www.[domain.com]/

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^www\.|assets\.|payloads\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

While this checks if HTTPS is not on AND a proper subdomain is found, then redirects to https://[subdomain].[domain.com]/

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.|assets\.|payloads\. [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Although the first condition/rule set successfully redirects to the default www subdomain, it goes into a loop and nothing displays when going to https://www.[domain.com].

Can someone explain what's wrong with my logic? I've looked at other answers here and either they don't help or there are no answers.

If it's more appropriate to force HTTPS in httpd.conf, and leave the redirects to the .htaccess, I can do that as well.

Thanks in advance.

Upvotes: 1

Views: 136

Answers (1)

anubhava
anubhava

Reputation: 785571

You can accomplish with these 2 rules in httpd.conf or vhost.cong or site root .htaccess:

RewriteEngine On

# for assets or payload subdomains
RewriteCond %{HTTP_HOST} ^(?:assets|payloads)\. [NC]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

# for rest
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Upvotes: 1

Related Questions