Last active
September 26, 2023 12:08
-
-
Save Calinou/fc0fe1003c95380054f0084f9476e476 to your computer and use it in GitHub Desktop.
Apache configuration to serve precompressed Brotli files. Precompression script: https://gist.github.com/Calinou/30f21f07017d908fc74c7eccb3f469c3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Serve precompressed Brotli files if they exist. | |
## Adapted from <https://stackoverflow.com/questions/46487635/how-to-serve-precompressed-gzip-brotli-files-with-htaccess> | |
## Make sure `RewriteBase /` is present somewhere in your .htaccess file. | |
# If the web browser accepts Brotli encoding... | |
RewriteCond %{HTTP:Accept-encoding} br | |
# ...and the web browser is fetching a probably pre-compressed file... | |
RewriteCond %{REQUEST_URI} .*\.(css|html|js|svg|wasm) | |
# ...and a matching pre-compressed file exists... | |
RewriteCond %{REQUEST_FILENAME}.br -s | |
# ...then rewrite the request to deliver the Brotli file. | |
RewriteRule ^(.+) $1.br | |
# For each file format set the correct MIME type. Otherwise, the Brotli mime type is returned. | |
# Also prevent Apache from recompressing the files. | |
RewriteRule "\.css\.br$" "-" [T=text/css,E=no-brotli,E=no-gzip] | |
RewriteRule "\.html\.br$" "-" [T=text/html,E=no-brotli,E=no-gzip] | |
RewriteRule "\.js\.br$" "-" [T=application/javascript,E=no-brotli,E=no-gzip] | |
RewriteRule "\.svg\.br$" "-" [T=image/svg+xml,E=no-brotli,E=no-gzip] | |
RewriteRule "\.wasm\.br$" "-" [T=application/wasm,E=no-brotli,E=no-gzip] | |
<FilesMatch "\.(css|html|js|svg|wasm)\.br$"> | |
# Prevent mime module from setting Brazilian language header (because the file ends with .br). | |
RemoveLanguage .br | |
# Set the correct encoding type. | |
Header set Content-Encoding br | |
# Force proxies to cache Brotli and non-Brotli files separately. | |
Header append Vary Accept-Encoding | |
</FilesMatch> | |
## Set cache headers. | |
## We don't have a cache busting setup yet, so use a short cache duration, allow using stale assets immediately but revalidate in the background. | |
## Note: `stale-while-revalidate` is currently only supported in Chromium-based browsers. | |
## `immutable` is still used to improve the user experience on Firefox and Safari. | |
<FilesMatch "\.(br|css|js|svg|wasm|pck|jpeg|jpg|png|gif|ico|webp|mp4|webm|woff|woff2)$"> | |
Header set Cache-Control "max-age=86400, stale-while-revalidate=31536000, public, immutable" | |
</FilesMatch> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment