How can I update .htaccess to conditionally gzip on-the-fly - apache

Note
Someone suggested that this is a duplicate of How to serve precompressed gzip/brotli files with .htaccess. That question seeks only to serve pre-compressed files. This question is different. Please see below.
My Goal
I want to serve pre-compressed brotli files when they exist. If no pre-compressed brotli file exists, fall back to on-the-fly gzip-compression.
Current Code
I'm working on a site that already has on-the-fly gzip enabled from its .htaccess file as follows:
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml...
</ifmodule>
Modified Code
I've setup a build script that compresses many static assets with brotli. In order to serve them, I've replaced the above mod_deflate block with the following:
<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-brotli:1]
RewriteRule "\.js\.br$" "-" [T=text/javascript,E=no-brotli: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>
The Problem
This serves brotli-encoded files when they exist as expected. However, the problem I face now is that, because the remaining assets are not brotli-encoded at build time, they are now served with no compression.
I've been unable to figure out how I might serve brotli with a gzip fallback that does not require me to pre-compress for gzip output.
Any help is appreciated, thank you!

Your problem is you’ve replaced the dynamic gzip config with the static.
You need both bits of config in place but also to change your Brotli code to set the environment to no-gzip so it won’t fallback. The below should work;
<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>

Related

How to serve precompressed gzip/brotli files with .htaccess

Im trying to serve precompressed gzip/brotli files for html, js and css.
With the following code.
RewriteEngine on
# Brotli
# If the web browser accept brotli encoding…
RewriteCond %{HTTP:Accept-encoding} br
# …and the web browser is fetching a probably pre-compressed file…
RewriteCond %{REQUEST_URI} .*\.(css|html|js)
# …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 brotli mime type is returned) and prevent Apache for 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]
# Gzip
# If the web browser accept gzip encoding…
RewriteCond %{HTTP:Accept-Encoding} gzip
# …and the web browser is fetching a probably pre-compressed file…
RewriteCond %{REQUEST_URI} .*\.(css|html|js)
# …and a matching pre-compressed file exists…
RewriteCond %{REQUEST_FILENAME}.gz -s
# …then rewrite the request to deliver the gzip file
RewriteRule ^(.+) $1.gz
# For each file format set the correct mime type (otherwise gzip mime type is returned) and prevent Apache for recompressing the files
RewriteRule "\.css\.gz$" "-" [T=text/css,E=no-brotli,E=no-gzip]
RewriteRule "\.html\.gz$" "-" [T=text/html,E=no-brotli,E=no-gzip]
RewriteRule "\.js\.gz$" "-" [T=application/javascript,E=no-brotli,E=no-gzip]
<FilesMatch "\.(css|html|js)\.br$">
# Prevent mime module to set 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 & non-brotli files separately
Header append Vary Accept-Encoding
</FilesMatch>
<FilesMatch "\.(css|html|js)\.gz$">
# Serve correct encoding type
Header set Content-Encoding gzip
# Force proxies to cache gzip & non-gzip files separately
Header append Vary Accept-Encoding
</FilesMatch>
My Folderstructure looks like this:
.htaccess
index.php
/css/
/css/main.css
/css/main.css.gz
/css/main.css.br
But I get 404s when using the code above.
Setting the RewriteBase fixed it.
RewriteBase /
Writing this to help others. I had to add %{DOCUMENT_ROOT} in the RewriteCond to get it to work.
Essentially, change all RewriteCond to
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME}\.br -s
For me the problem was, that brotli compression is not supported for http connections. See Why is Brotli not supported on HTTP?

Get Apache to auto-decompress a file, but only if needed

I'd like to keep all the static files of my web-server locally compressed, and to serve them either compressed or not, depending on the request.
The answers in How can I pre-compress files with mod_deflate in Apache 2.x? , are close, since indeed by enabling MultiViews and using the right AddEncoding, I can get Apache to return me the compressed foo.tar.gz file from my web-server when I request foo.tar, and it comes with the proper Content-Encoding: header.
But this only works if the client includes Accept-Encoding: gzip in the headers it sends to the server. OTOH if the client does not support the gzip encoding, my server just tells me there's no "acceptable" foo.tar for me.
I can get Apache to decompress that tarball before sending it if I use AddOutputFilter INFLATE tar. But if I do that, then the server also decompresses the content when I request foo.tar.gz (or when I specify that I accept the gzip encoding), which I clearly don't want.
So how do I get Apache to decompress the files when the client doesn't support the gzip content-encoding, but to serve the pre-compressed file in the other cases?
EDIT: Based on #covener's suggestion I tried the following:
AddEncoding x-gzip .gz .tgz
RemoveType application/x-gzip .gz .tgz
AddType application/x-tar .tgz
<Location /packages>
FilterDeclare smgunzip CONTENT_SET
FilterProvider smgunzip INFLATE req=Accept-Encoding !$gzip
FilterChain smgunzip
</Location>
[ Using Apache-2.2.22 here. ] But the result is actually worse than with just the first three lines: when I request the .tar.gz file, it now gets returned without the "Content-Encoding:", and when I request the .tar file, I receive the content of the tar.gz (i.e. still compressed) regardless of the "Accept-Encoding:" header and still without the "Content-Encoding:".
(make sure you have AddEncoding gzip or x-gzip gz or it will break)
2.4:
<Directory /home/covener/SRC/2.4.x/built/htdocs>
Options +MultiViews
MultiviewsMatch Any
FilterDeclare gzip CONTENT_SET
FilterProvider gzip INFLATE "! req('Accept-Encoding') =~ /gzip/"
FilterChain gzip
</Directory>
2.2:
<Directory /home/covener/SRC/2.2.x/built/htdocs>
Options +MultiViews
MultiviewsMatch Any
FilterDeclare gzip CONTENT_SET
FilterProvider gzip INFLATE req=Accept-Encoding !$gzip
FilterChain gzip
</Directory>
Try this:
DirectoryIndex "index.html.gz" "index.html"
# Don't list the compressed files in directory indexes - you probably don't want to expose
# the .gz URLs to the outside. They're also misleading, since requesting them will give the
# original files rather than compressed ones.
IndexIgnore "*.html.gz" "*.css.gz"
RewriteEngine On
# Rewrite requests for .html/.css files to their .gz counterparts, if they exist.
RewriteCond "%{DOCUMENT_ROOT}%{REQUEST_FILENAME}.gz" -s
RewriteRule "^(.*)\.(html|css)$" "$1\.$2\.gz" [QSA]
# Serve compressed HTML/CSS with the correct Content-Type header.
RewriteRule "\.html\.gz$" "-" [T=text/html,E=no-gzip:1]
RewriteRule "\.css\.gz$" "-" [T=text/css,E=no-gzip:1]
# Define a filter which decompresses the content using zcat.
# CAVEAT: This will fork a new process for every request made by a client that doesn't
# support gzip compression (most browsers do), so may not be suitable if you're running a
# very busy site.
ExtFilterDefine zcat cmd="/bin/zcat -"
<FilesMatch "\.(html|css)\.gz$">
<If "%{HTTP:Accept-Encoding} =~ /gzip/">
# Client supports gzip compression - pass it through.
Header append Content-Encoding gzip
</If>
<Else>
# Client doesn't support gzip compression - decompress it.
SetOutputFilter zcat
</Else>
# Force proxies to cache gzipped & non-gzipped css/js files separately.
Header append Vary Accept-Encoding
</FilesMatch>
Cribbed from Daniel Collins, Serving static gzip-compressed content with Apache.

where to set header for access control origin in apache

Have added/set the header for access control in .htaccess file of the directory where the web application is present (drupal) . but when making a ajax request for it with jquery, the console error gives following message:
XMLHttpRequest cannot load http://localhost/drupal/get/news.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:56687' is therefore not allowed access.
the .htaccess is insider the folder "drupal" and the header is set at the following:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
# Serve gzip compressed CSS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.css $1\.css\.gz [QSA]
# Serve gzip compressed JS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.js $1\.js\.gz [QSA]
# Serve correct content types, and prevent mod_deflate double gzip.
RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
<FilesMatch "(\.js\.gz|\.css\.gz)$">
# Serve correct encoding type.
Header set Content-Encoding gzip
# Force proxies to cache gzipped & non-gzipped css/js files separately.
Header append Vary Accept-Encoding
</FilesMatch>
</IfModule>
</IfModule>
Any help will be appreciated.
XMLHttpRequest cannot load http://localhost/drupal/get/news.
The above means that in your Drupal CMS, you have references pointing to your localhost. My guess is that you constructed your site locally, and then migrated to a live server, but in doing so, some of the references are not yet changed. I would recommend you to replace all http://localhost instances in your .sql file with http://yourdomain.com since the files are meant to be publicly available and no one else can access your localhost resources from outside network.

Conditionally gzip files based on available compression library

I am trying to set up gzip compression on a website, but we are not sure where it will be hosted and I want to be able to support mod_gzip if it's available.
What I'd like to do is something like this:
<IfModule mod_gzip.c>
# mod_gzip rules
<IfOtherModule mod_deflate.c>
# mod_deflate rules
</IfModule>
Do apache configs allow this? Is mod_deflate smart enough not to work if mod_gzip has already done its thing?
<IfModule mod_gzip.c>
# mod_gzip rules
</IfModule>
<IfModule !mod_gzip.c>
<IfModule mod_deflate.c>
# mod_deflate rules
</IfModule>
</IfModule>
Although I would change the order around and first try mod_defate. mod_gzip is no longer under development so you are better of using mod_deflate (which by the way also uses gzip, and not deflate, as the name might suggest).

How to serve a gziped font using .htaccess? (no mod gzip or deflate)

Here's a list of stuff I tried in random order:
AddHandler application/x-httpd-php .otf
AddType
default_mimetype
auto_prepend_file = "otf.php"
zlib.output_compression = On
output_handler = ob_gzhandler
header("Content-type: application/octet-stream");
Even though all the PHP files of the server get gzipped using zlib, replacing the .otf extension by .php didn't work either.
With .htaccess, you could do like this, assuming font file is fontfile.otf.gz, browser request that as fontfile.otf
RewriteEngine On
#Check for browser's Accept-Encoding, remove it for force return gzipped one
RewriteCond "%{HTTP:Accept-Encoding}" "gzip.*deflate|deflate.*gzip"
#check file name is endswith otf
RewriteCond %{REQUEST_FILENAME} "\.(otf)$"
#check existance of .gz file name
RewriteCond %{REQUEST_FILENAME}.gz -s
#rewrite it to .otf.gz
RewriteRule ^.*$ %{REQUEST_URI}.gz [L]
#update some response header
<FilesMatch "\.otf\.gz$">
AddEncoding gzip .gz
ForceType "text/plain"
</FilesMatch>
And if font file and web site is cross-domain, you need to put Access-Control-Allow-Origin, firefox will not load font objects cross-domain.
In Gecko, web fonts are subject to the
same domain restriction (font files
must be on the same domain as the page
using them), unless HTTP access
controls are used to relax this
restriction.
Header set Access-Control-Allow-Origin *