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).
Related
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>
Having issues setting up a generic Allow Origin for any subdomain in my .htaccess file. The following works for a singular subdomain:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin http://subdomain.website.com
</IfModule>
But what I am looking for is something similar to this:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin {ANY SUBDOMAIN}.website.com
</IfModule>
I have tried using a simple *.website.com wildcard, but that does not seem to work. Do you have to specify exactly what is coming in?
If you're looking to do it for whatever subdomain was being requested, try the following:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin %{HTTP_HOST}
</IfModule>
If you need something more advanced, use mod_rewrite to set an environment variable and then refer to it using %{variable_name}e
A few days ago I had a problem with writing my first htaccess in order to remove .html extension from URL. There were problems because I had a Windows server which I changed to Linux.
Now the issue is this:
I finally did manage to remove the .html extension from URL. What I can't do is to set an expiration date for all images (JPEG, PNG, SVG).
My working code is this (extension removal):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
For Image caching parameter I added the following:
//Caching schema
<FilesMatch "\.(jpg|png|svg)$">
Header set Cache-Control "private, max-age=160704000"
</FilesMatch>
When I added the additional code above I got an internal server error.
I don't know what's going on to be honest. If I remove this additional code it will work but if I add this then it wont.
So do you guys have any ideas of how to add an Image caching parameter?? The additional code above doesn't work :(
UPDATE
After some research I tried this one:
<ifModule mod_headers.c>
ExpiresActive On
# Expires after 1 month
<filesMatch ".(gif|png|jpg|jpeg|ico|pdf|js|htm|html|txt)$">
Header set Cache-Control "max-age=2592000"
</filesMatch>
# Expires after 1 day
<filesMatch ".(css)$">
Header set Cache-Control "max-age=86400"
</filesMatch>
</ifModule>
Surprisingly this works. I tested it with gtmetrix.com .You think I should move forward now?
Set AllowOverride All in your server config for the host. Do this for the directory where your htaccess resides rather than the whole server, e.g.
<Directory /var/www/html/mysite/>
AllowOverride All
</Directory>
The issue is that your syntax is valid, but the server is refusing to process the request because AllowOverride is set to something other than 'All' which is what FilesMatch requires.
If you don't want to set AllowOverride to All for the .htaccess file, then you could move the <FilesMatch> statement into the host configuration for your site and it will work from there.
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.
I have KOHANA_ENV environment var set to DEVELOPMENT for example. Now there is a set of rules I'd like to apply only if that var is set to PRODUCTION (turn on mod_deflate, set expires headers defaults, turn off ETags, etc.), like:
if (KOHANA_ENV == PRODUCTION) {
// .. do stuff
}
Is there a way to do this on Apache level at all or it's better to have two conf files?
I do it with the help of the great module mod_macro.
Let's say you have in /etc/apache2/envvars (for a Debian-like distribution it's the place to store apache environnement variables):
#export KOHANA_ENV=PROD
export KOHANA_ENV=DEV
Where you [un]coment depending on production or development.
In the other side you have your VirtualHost, or just a part of it defined with a macro. Macro is the way to write a generic configuration part with some variables. I use it for complete Virtualhosts but here's an example with just a part of a VirtualHost. We'll use the environnement variable to decide which macro to use (keyword Use):
<Virtualhost *:80>
ServerName foobar.com
#(...)
Use EnvStuff_${KOHANA_ENV} /tmp
#(...)
Here the macro takes an argument (tmp directory path) it's not an obligation.
Then you should only define 2 different macro where the environnement variable is part of the macro name EnvStuff_PROD & EnvStuff_DEV:
<Macro EnvStuff_PROD $tmp>
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
</IfModule>
<IfModule mod_headers.c>
Header set MyHeader "Hello this is PRODUCTION envirronment. It took %D microseconds for Apache to serve this request."
# 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]
#(...)
</IfModule>
php_admin_value upload_tmp_dir $tmp/upload
#(... other php settings for production)
</Macro>
<Macro EnvStuff_DEV $tmp>
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive Off
</IfModule>
<IfModule mod_headers.c>
Header set MyHeader "Hello this is DEVELOPMENT envirronment. It took %D microseconds for Apache to serve this request."
</IfModule>
php_admin_value upload_tmp_dir $tmp/upload
</Macro>
In these examples you can checkl headers in responses and you'll see easily if it worked for you.
Be careful, if the environnement variable is not set well, you'll get some problems, maybe you can create a macro EnvStuff_ as well :-)