HTTP headers with .htaccess
Published
Updated
Control HTTP response headers with .htaccess.
The `Header` directive in `.htaccess` adds response headers before Apache sends a file. Use it for browser caching of static assets, CORS for APIs and security headers. `mod_headers` is loaded on fortrabbit; `mod_expires` is not.
Cache-Control
Cache-Control tells browsers how long to keep a file. ExpiresByType from mod_expires is not available on fortrabbit and causes a 500 error; set the header directly:
<IfModule mod_headers.c>
# Fingerprinted build output: one year
<FilesMatch "\.(css|js|woff2)$">
Header set Cache-Control "max-age=31536000, immutable"
</FilesMatch>
# Images: one month
<FilesMatch "\.(avif|gif|ico|jpe?g|png|svg|webp)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>
</IfModule>
A browser does not ask for a cached file again until max-age runs out. A changed file under the same name reaches visitors only after that. immutable and a long max-age therefore suit only files with a hash in the name, such as app.4f3a2c.css from Vite or Laravel Mix. Many CMS and frameworks set these headers themselves; check the response in the network tab of the browser's developer tools first.
CORS
Browsers block JavaScript on one domain from reading responses from another domain, unless the response allows it. Allow one origin:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "https://app.example.com"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>
Access-Control-Allow-Origin "*" allows every site, but browsers reject it for requests that send cookies or other credentials. Most frameworks have a CORS setting that also answers the OPTIONS preflight request; prefer it for an API.
Security headers
<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set X-Frame-Options "SAMEORIGIN"
</IfModule>
always adds the header to error responses too. HSTS and a Content Security Policy go in the same block; see content-security-policy.com for the policy syntax.