Sunday 18 August 2019

Gzip, gzip for webpack, configure apache or ngnix to serve gzip

How to find if server side content is gziped:

If you find Content-Encoding: gzip in the response over head list, then the page is gzip-compressed.


Compression webpack plugin to gzip content, so you get bundle.js.gz instead of bulndle.js

production gzip in vue cli 3.0
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']

configureWebpack: {
        plugins: [
            new CompressionWebpackPlugin({
                asset: '[path].gz[query]',
                algorithm: 'gzip',
                test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
                threshold: 10240,
                minRatio: 0.8
            })
        ]
    }


configure apache or ngnix to serve gzip if gzip exists and client accept gzip, if not serve original

nginx:
Open /etc/nginx/conf.d provide below configuration .
server {
    gzip on;
    gzip_static on;    
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_proxied  any;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;    
    ...
}
To send a compressed version of a file to the client instead of the regular one, set the gzip_staticdirective to on within the appropriate context.
In this case, to service a request for /path/to/bundle.js, NGINX tries to find and send the file /path/to/bundle.js.gz. If the file doesn’t exist, or the client does not support gzip, NGINX sends the uncompressed version of the file.
Note that the gzip_static directive does not enable on-the-fly compression. It merely uses a file compressed beforehand by any compression tool. To compress content (and not only static content) at runtime, use the gzip directive.
Save and close the file to exit.
To enable the new configuration, restart Nginx.
$sudo service nginx restart

Apahce(.htaccess):
# AddEncoding allows you to have certain browsers uncompress information on the fly.
AddEncoding gzip .gz

#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]


No comments:

Post a Comment