redirect all subdomains from http to https redirect all subdomains from http to https apache apache

redirect all subdomains from http to https


You could add this to your server's .conf file:

<VirtualHost *:80>  ServerName subdomain.example.com  ServerAlias *.example.com  RewriteEngine On  RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$  RewriteRule ^(.*)$ https://%1.example.com$1 [R=302,L]</VirtualHost>

The ServerAlias will allow the vhost to act as a wildcard, then you can extract the subdomain(s) from the host header and include them in the rewrite to https


Here is a simpler universal modification to the .conf file:

<VirtualHost *:80>    #...whatever you already have set up...    RewriteEngine On    RewriteCond %{HTTP_HOST} ^(.*)$ [NC]    RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]</VirtualHost>


As the Apache Wiki entry for RewriteHTTPToHTTPS states,

Using mod_rewrite to do this isn't the recommended behavior. See RedirectSSL

The vhost configuration for forced HTTP to HTTPS redirection - that also works with subdomains - is this:

<VirtualHost *:80>    ServerName example.com    ServerAlias *.example.com    <Location "/">        Redirect permanent "https://%{HTTP_HOST}%{REQUEST_URI}"    </Location></VirtualHost><VirtualHost *:443>    [...your vHost configuration...]    SSLEngine On    SSLCertificateFile /path/to/your/cert.pem    SSLCertificateKeyFile /path/to/your/privkey.pem</VirtualHost>

Explanation: Redirect and RedirectMatch normally don't have the variables (like {HTTP_HOST}) from Mod_Rewrite but if you use <Location > these Variables will be assigned.

Redirect permanent (Alternative: Redirect 301) will redirect with a http 301 code, because

The 301 redirect is considered a best practice for upgrading users from HTTP to HTTPS.

Note: This config is based on Wildcard Certificates for subdomains.