Repository navigation
Expand file tree
/
Copy pathhttps-enforcement.htaccess
More file actions
43 lines (38 loc) · 1.62 KB
/
Copy pathhttps-enforcement.htaccess
File metadata and controls
43 lines (38 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# HTTPS Enforcement (Apache / .htaccess)
#
# What this does:
# Redirects all HTTP requests to HTTPS, preserving host, path, and
# query string. This is the one case where RewriteRule is the right
# tool - mod_alias cannot test the connection scheme.
#
# When to use it:
# Any site served over HTTPS. Add HSTS so browsers skip HTTP entirely
# on return visits.
#
# Notes:
# Requires mod_rewrite (and mod_headers for HSTS). Enable with:
# a2enmod rewrite headers
RewriteEngine On
# If the request did not arrive over HTTPS, redirect to the HTTPS URL.
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Behind a proxy/load balancer that terminates TLS, test the forwarded
# header instead (comment out the block above and use this):
# RewriteCond %{HTTP:X-Forwarded-Proto} =http
# RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Tell browsers to stay on HTTPS for a year.
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>
# Example:
# Before: http://example.com/cart?id=7
# After: https://example.com/cart?id=7 (HTTP 301)
#
# Gotchas:
# - %{HTTP_HOST} preserves www vs apex as requested; %{REQUEST_URI}
# preserves path + query, so nothing is lost.
# - [L] stops rewrite processing; [R=301] sends the permanent redirect.
# - Do not add HSTS `preload`/`includeSubDomains` until every subdomain
# is HTTPS - it is very hard to roll back once browsers cache it.
# - `RewriteCond %{HTTPS} off` only works when Apache terminates TLS;
# behind a CDN, use the X-Forwarded-Proto variant above.