I am currently working on an application which was build to work with wildcard subdomains.
For Example:
customer1.domain.com
customer2.domain.com
So we bought a wildcard SSL Certificate for *.domain.com and redirected all subdomains from http to https.
So far, so easy, but now we have customers that manually type www.customer1.domain.com in their browser, for this exists no vhost.
What i want to do now is, redirect all request from http://www.wildcard.domain.com to https://wildcard.domain.com
Our vhost looks like:
<VirtualHost {{IP-ADRR}}:443>
Servername %1.domain.com
VirtualDocumentRoot /path/to/webroot/%0
Include /etc/httpd/conf/options-ssl-standard.conf
</VirtualHost>
Our Redirect for all HTTP Request to same target on HTTPS looks like:
<Virtualhost {{IP-ADRR}}:80>
ServerName %1.domain.com
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
</VirtualHost>
The solution for the redirect is:
<Virtualhost {{IP-ADRR}}:80>
ServerName %1.domain.com
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
</VirtualHost>
Explanation:
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
These two lines are are the redirect conditions, they are used to determine if the request should be redirected. Because the conditions are joined with an [OR], if any of those two conditions returns true, Apache will execute the rewrite rule (the redirect).
The first condition determines if the request is using a non-HTTPS URL. The second condition determines if the request is using the www URL. Notice that I used www\. and not www., because the pattern is a regular expression and the . dot has a special meaning here, hence it must be escaped.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
The forth line is a convenient line I used to avoid referending the hostname directly in the URL. It matches the HOST of the incoming request, and decomposes it into www part (if any), and rest of the hostname. We'll reference it later with %1 in the RewriteRule.
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]
The RewriteRule is the heart of the redirect. With this line we tell Apache to redirect any request to a new URL, composed by:
All these tokens are joined together, and represents the final redirect URI. Finally, we append 3 flags: