Enable Brotli Compressing using .htaccess file

Enable Brotli Compressing using .htaccess file

To check if Brotli is enabled on the server for the current PHP version:

php -m | grep brotli

To use it on the website add the following to the beginning of the .htaccess file:

<ifmodule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml...
</ifmodule>

<IfModule mod_headers.c>
    # Serve brotli compressed CSS and JS files if they exist
    # and the client accepts brotli.
    RewriteCond "%{HTTP:Accept-encoding}" "br"
    RewriteCond "%{REQUEST_FILENAME}\.br" "-s"
    RewriteRule "^(.*)\.(js|css)"              "$1\.$2\.br" [QSA]

    # Serve correct content types, and prevent double compression.
    RewriteRule "\.css\.br$" "-" [T=text/css,E=no-gzip:1]
    RewriteRule "\.js\.br$"  "-" [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.br|\.css\.br)$">
        # Serve correct encoding type.
        Header append Content-Encoding br

        # Force proxies to cache brotli &
        # non-brotli css/js files separately.
        Header append Vary Accept-Encoding
    </FilesMatch>
</IfModule>

To check if website is supporting Brotli use a free tool such as https://www.giftofspeed.com/gzip-test/

image 1024x613 - Enable Brotli Compressing using .htaccess file

or browse the website and inspect the response of .js and .css files – look for content-encoding: br

image 1 1024x434 - Enable Brotli Compressing using .htaccess file
whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.