HTTP headers
Reviewedbyfl
Markdown ↓Control HTTP response headers with .htaccess.
HTTP headers are part of a Hyper Text Transfer Protocol request and response. Use htaccess to control caching, CORS, and other operating parameters of HTTP transactions.
Cache-Control
Use Cache-Control headers to instruct browsers how long to cache static assets locally. This reduces server requests and bandwidth usage, improving performance. In your .htaccess you can set max-age values per file type, caching images longer than stylesheets.
Don't serve the same content to the same client twice! You can control the caching in htaccess like so:
# Example to cache images and CSS files
# adjust and extend to your needs
<ifModule mod_headers.c>
# images expire after 1 month
<filesMatch "\.(gif|png|jpg|jpeg|webp|ico|pdf|svg|js)$">
Header set Cache-Control "max-age=2592000"
</filesMatch>
# CSS expires after 1 day
<filesMatch "\.(css)$">
Header set Cache-Control "max-age=86400"
</filesMatch>
</ifModule>
If you are using a CMS this is usually already managed for you in PHP code. You can open the web inspector on your website, go to the network tab and check the headers for any images, to see if they already have cache headers.
Beware: Adding this also introduces the main problem of caching. If you later decide to change the image or CSS file, you must either wait the full cache time, or give the file a new name to make the browser retrieve it again. Otherwise it will use the old cached version.
CORS headers
CORS (Cross-Origin Resource Sharing) headers enable JavaScript on one domain to request resources from another domain securely. Without CORS headers, browsers block cross-domain requests by default for security. In your .htaccess you can selectively permit specific origins or all origins using Access-Control-Allow-Origin headers.
For "Cross-Site XMLHttpRequests" you'll need CORS headers. By default this is not possible for security reasons. But you can enable it for certain or even all origins:
# Access all areas (use carefully)
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"
Use this with care and only open what you really need. Reduce the risk of XSS. Also check out the new Content Security Policy (CSP) for more advanced control on what you allow and what not. This website is a good reference: content-security-policy.com