redirect all subdomains from http to https

Super Engineer picture Super Engineer · Apr 14, 2014 · Viewed 17.5k times · Source

I redirect all http requests for my subdomain to https by using following code.

<VirtualHost *:80>
  ServerName subdomain.example.com
  Redirect 302 / https://subdomain.example.com
</VirtualHost>

Now my problem is how do I do it for all subdomains.

For example http:subdomain1.example.com should go to https:subdomain1.example.com and http:subdomain2.example.com should go to https:subdomain2.example.com

How do I do it for all subdomains without having to create one virtualhost for all of them

Update

I found that RedirectMatch takes regular expression. Does anyone know how to do it using regex?

Answer

arco444 picture arco444 · Apr 14, 2014

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