2

I'm looking to add the HSTS header in Apache...

# HSTS / Header Strict Transport Security
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"

... but I have a long list of vhosts for different but related sites/sub-sites. I'd rather not have to define it in every one of my vhost definitions, but I'm not aware of a way to include a setting in the main https.conf that ONLY applies to the 443 / https versions of those vhosts since it raises warnings in validators when you apply HSTS to a standard 80 / http site.

I've tried wrapping it in <IfModule mod_ssl.c>...</IfModule> tags but if I'm not mistaken, this is really just asking Is the SSL module loaded? I tried searching lots of different ways, but when you don't know the term your looking for, it's difficult to sort through all the static. Any suggestions? Thanks!

oucil
  • 445
  • 3
  • 16

1 Answers1

2

You can do this with the <If> Directive and the Expressions available; request related variables:

  • REQUEST_SCHEME: The scheme part of the request's URI

    <If "%{REQUEST_SCHEME} == 'https'">
      Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
    </If>
    
  • HTTPS: on if the request uses https, off otherwise

    <If "%{HTTPS} == 'on'">
      Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
    </If>
    
Esa Jokinen
  • 43,252
  • 2
  • 75
  • 122
  • Thanks very much for that, I'd used them in PHP many times before forgetting that they came from Apache! One note, the value for `REQUEST_SCHEME` should be lower case `https`, it won't ever match `HTTPS`. Cheers! – oucil Jun 16 '20 at 07:02
  • 1
    Thanks for the correction. I've updated the lowercase `https`. – Esa Jokinen Jun 16 '20 at 07:05