Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HSTS header from .htaccess only on HTTPS [closed]

My web application runs on a different number of hosts that I control. To prevent the need to change the Apache config of each vhost, I add most of the config using .htaccess files in my repo so the basic setup of each host is just a couple of lines. This also makes it possible to change the config upon deploying a new version. Currently the .htaccess (un)sets headers, does some rewrite magic and controls the caching of the UA.

I want to enable HSTS in the application using .htaccess. Just setting the header is easy:

Header always set Strict-Transport-Security "max-age=31536000" 

But the spec clearly states: "An HSTS Host MUST NOT include the STS header field in HTTP responses conveyed over non-secure transport.". So I don't want to send the header when sending it over HTTP connections. See https://datatracker.ietf.org/doc/html/draft-ietf-websec-strict-transport-sec-14 .

I tried to set the header using environment vars, but I got stuck there. Anyone that knows how to do that?

like image 472
nielsr Avatar asked Jun 10 '14 15:06

nielsr


People also ask

How do I resolve HSTS missing from HTTPS server?

Use your browsers developer tools or a command line HTTP client and look for a response header named Strict-Transport-Security. Access your application once over HTTPS, then access the same application over HTTP. Verify your browser automatically changes the URL to HTTPS over port 443.


2 Answers

Apparently there is a HTTPS environment variable available that can be used easily. For people with the same question:

Header set Strict-Transport-Security "max-age=31536000" env=HTTPS 
like image 162
nielsr Avatar answered Sep 24 '22 19:09

nielsr


To build on nielsr's answer, I used the following in the .htaccess to meet the secure deployment recommendations at https://hstspreload.org which will hardcode the domain into the Chrome browser. Be aware this will enforce HSTS across your subdomains, and that inclusion in the preload list cannot easily be undone, so rtfm.

<IfModule mod_headers.c> Header set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" env=HTTPS </IfModule> 
like image 40
LJT Avatar answered Sep 24 '22 19:09

LJT