human human - 6 days ago 4x
Apache Configuration Question

Redirect from HTTP to HTTPS but not for subdomains

I have a site that contains subdomains, I have installed a SSL certificate, and I want HTTP requests to be redirected to HTTPS, however I don't want subdomains to be redirected to HTTPS except a couple: and which have to be HTTPS.

I have setup the code below, however it doesn't handle subdomains, my subdomains are currently redirecting to the HTTPS version of the root domain.

NameVirtualHost *:80
<VirtualHost *:80>
ServerAlias *
Redirect permanent /

<VirtualHost _default_:443>

How shall I do this?

Edit: To be a bit more specific.
How can I...?



This can pretty easily be done with mod_rewrite.

RewriteCond %{HTTPS} =off
RewriteCond %{HTTP_HOST} "^(((app|api)\.)?example\.com)$"
RewriteRule ^/(.*)$ https://%1/$1 [R,L]

The first condition ensures the rule is only triggered for non-HTTPS requests. This can be omitted if you put the rule in your port 80 vhost and only accept non-HTTPS requests on that port.

The second condition inspects the HOST header to ensure it's,, or

The rule itself issues a redirect to the HTTPS counterpart. %1 is a backreference to the full HOST header contents (%0 could work here as well and allow you to omit some parens) and $1 is a backreference to the path (minus the leading forward slash).

NOTE: You can probably use the if directive as well to limit the redirect as desired.