How To Enable Gzip Compression
GZIP compression is used to reduce the traffic between the web servers and the browser. By using GZIP we can reduce the sizes of the files such as HTML, JavaScript, JSP and images upto 70% of file size. Enabling GZIP in servers is as easy as turning on a switch. GZIP reduces the size of the named files using Lempel–Ziv coding (LZ77). Whenever possible, each file is replaced by one with the extension ‘.gz’, while keeping the same ownership modes, access and modification times.
Gzip is lossless compression data, we can restore the original data once decompressed.
Downloading GZIP
GZIP can be found on the main GNU ftp server: http://ftp.gnu.org/gnu/gzip/ (via HTTP).
Here are some realistic examples of running gzip
.
This is the output of the command ‘gzip -h’:
Usage: gzip [OPTION]... [FILE]... Compress or uncompress FILEs (by default, compress FILES in-place). Mandatory arguments to long options are mandatory for short options too. -c, --stdout write on standard output, keep original files unchanged -d, --decompress decompress -f, --force force overwrite of output file and compress links -h, --help give this help -k, --keep keep (don't delete) input files -l, --list list compressed file contents -L, --license display software license -n, --no-name do not save or restore the original name and timestamp -N, --name save or restore the original name and timestamp -q, --quiet suppress all warnings -r, --recursive operate recursively on directories --rsyncable make rsync-friendly archive -S, --suffix=SUF use suffix SUF on compressed files --synchronous synchronous output (safer if system crashes, but slower) -t, --test test compressed file integrity -v, --verbose verbose mode -V, --version display version number -1, --fast compress faster -9, --best compress better With no FILE, or when FILE is -, read standard input. Report bugs to <[email protected]>.
use above commands to compress the files directories directly.
How to Enable GZIP Compression in Java Servlets as Filters for Web Application
Create a Filter and corresponding class as mentioned in below steps,
public class CompressionFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String acceptEncoding = httpRequest.getHeader(HttpHeaders.ACCEPT_ENCODING); if (acceptEncoding != null) { if (acceptEncoding.indexOf("gzip") >= 0) { GZIPHttpServletResponseWrapper gzipResponse = new GZIPHttpServletResponseWrapper(httpResponse); chain.doFilter(request, gzipResponse); gzipResponse.finish(); return; } } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { } }
public class GZIPHttpServletResponseWrapper extends HttpServletResponseWrapper { private ServletResponseGZIPOutputStream gzipStream; private ServletOutputStream outputStream; private PrintWriter printWriter; public GZIPHttpServletResponseWrapper(HttpServletResponse response) throws IOException { super(response); response.addHeader(HttpHeaders.CONTENT_ENCODING, "gzip"); } public void finish() throws IOException { if (printWriter != null) { printWriter.close(); } if (outputStream != null) { outputStream.close(); } if (gzipStream != null) { gzipStream.close(); } } @Override public void flushBuffer() throws IOException { if (printWriter != null) { printWriter.flush(); } if (outputStream != null) { outputStream.flush(); } super.flushBuffer(); } @Override public ServletOutputStream getOutputStream() throws IOException { if (printWriter != null) { throw new IllegalStateException("printWriter already defined"); } if (outputStream == null) { initGzip(); outputStream = gzipStream; } return outputStream; } @Override public PrintWriter getWriter() throws IOException { if (outputStream != null) { throw new IllegalStateException("printWriter already defined"); } if (printWriter == null) { initGzip(); printWriter = new PrintWriter(new OutputStreamWriter(gzipStream, getResponse().getCharacterEncoding())); } return printWriter; } @Override public void setContentLength(int len) { } private void initGzip() throws IOException { gzipStream = new ServletResponseGZIPOutputStream(getResponse().getOutputStream()); } }
public class ServletResponseGZIPOutputStream extends ServletOutputStream { GZIPOutputStream gzipStream; final AtomicBoolean open = new AtomicBoolean(true); OutputStream output; public ServletResponseGZIPOutputStream(OutputStream output) throws IOException { this.output = output; gzipStream = new GZIPOutputStream(output); } @Override public void close() throws IOException { if (open.compareAndSet(true, false)) { gzipStream.close(); } } @Override public void flush() throws IOException { gzipStream.flush(); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { if (!open.get()) { throw new IOException("Stream closed!"); } gzipStream.write(b, off, len); } @Override public void write(int b) throws IOException { if (!open.get()) { throw new IOException("Stream closed!"); } gzipStream.write(b); } }
Add the following filter implementation in web.xml
<filter> <filter-name>CompressionFilter</filter-name> <filter-class>com.my.company.CompressionFilter</filter-class> </filter> <filter-mapping> <filter-name>CompressionFilter</filter-name> <url-pattern>*.js</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CompressionFilter</filter-name> <url-pattern>*.css</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CompressionFilter</filter-name> <url-pattern>*.html</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CompressionFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>
Now the application is ready to perform compression using GZIP filter. Add HttpCore.Jar of any version which can be downloaded from http://hc.apache.org/downloads.cgi to build path if faced any exception in line,
String acceptEncoding = httpRequest.getHeader(HttpHeaders.ACCEPT_ENCODING);
How to Enable GZIP in WordPress Site
Enable Gzip using Apache
Enable Gzip compression in WordPress site is by editing your .htaccess file. Most shared hosts use Apache, in which you can simply add the code below to your .htaccess file. You can find your .htaccess file at the root of your WordPress site via FTP.
Important: Make sure mod_filter
is loaded on your server, otherwise the AddOutputFilterByType
directive will not work and could cause a 500 error. We recommend checking your error logs if you have any issues with the code below.
<IfModule mod_deflate.c> # Compress HTML, CSS, JavaScript, Text, XML and fonts AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE application/x-font AddOutputFilterByType DEFLATE application/x-font-opentype AddOutputFilterByType DEFLATE application/x-font-otf AddOutputFilterByType DEFLATE application/x-font-truetype AddOutputFilterByType DEFLATE application/x-font-ttf AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE font/opentype AddOutputFilterByType DEFLATE font/otf AddOutputFilterByType DEFLATE font/ttf AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE image/x-icon AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/xml # Remove browser bugs (only needed for really old browsers) BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html Header append Vary User-Agent </IfModule>
Ensure that you add it below the current contents of your .htaccess file. Example below:
# compress text, html, javascript, css, xml: AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript # Or, compress certain file types by extension: <files *.html> SetOutputFilter DEFLATE </files>
Apache actually has two compression options:
- mod_deflate is easier to set up and is standard.
- mod_gzip seems more powerful: you can pre-compress content.
Deflate is quick and works, so I use it; use mod_gzip if that floats your boat. In either case, Apache checks if the browser sent the “Accept-encoding” header and returns the compressed or regular version of the file. However, some older browsers may have trouble (more below) and there are special directives you can add to correct this.
Enable GZIP on NGINX
If you are running on NGINX, simply add the following to your nginx.conf file.
gzip on; gzip_disable "MSIE [1-6]\.(?!.*SV1)"; gzip_vary on; gzip_types text/plain text/css text/javascript image/svg+xml image/x-icon application/javascript application/x-javascript;
Enable GZIP on IIS
If you are running on IIS, there are two different types of compression, static and dynamic. We recommend checking out Microsoft’s guide on how to enable compression.
There are other options also available to use Gzip.
Verify Your Compression
Once you’ve configured your server, check to make sure you’re actually serving up compressed content.
- Online: Use the online gzip test to check whether your page is compressed.
- In your browser: In Chrome, open the Developer Tools > Network Tab (Firefox/IE will be similar). Refresh your page, and click the network line for the page itself (i.e.,
www.google.com
). The header “Content-encoding: gzip” means the contents were sent compressed.
Conclusion
We saw how to use Gzip in Java Servlets, WordPress, NGINX and IIS.