How To Auto-Minify JavaScript Files on Page Load in Apache Using UglifyJS

Minifying your JavaScript files is a way of securing your JavaScript codes and reducing your page size, this cannot be done while coding, we have tools for it. But what if you code hands-free and your server does the minifying for you since it’s the only one that serves what the web sees, a lot better? Well, lets head straight to it.


  • UglifyJS
  • mod_ext_filter
  • Apache

Install UglifyJS

Here, I’m running Ubuntu 14 or 15 with Apache2 installed; I will now install uglifyjs. UglifyJS is a JS minifying and beautifying tool.

sudo apt-get install uglifyjs

Now, to verify my uglifyjs installation I’ll type:

uglifyjs –help


UglifyJS installed successfully, now I’ll activate mod_ext_filter. This is an Apache module for filtering input and output of the Apache server; we need this module so I’ll activate it because it is deactivated by default apache installation.

In Ubuntu:

sudo a2enmod ext_filter


Then restart apache2.

Other distros:

Create a symbolic link of ext_filter.load from mods-available to mod-enabled as below:

sudo ln -s /etc/apache2/mods-available/ext_filter.load /etc/apache2/mods-enabled/

Setting up Minifying

Now I have uglifyjs and mod_ext_filter set up, I now will create a config file that minifies JS files only. I’m creating js-minify.conf in /etc/apache2/conf-available/ and I’ll paste it in this code

<IfModule mod_ext_filter.c>
ExtFilterDefine jsminify\
intype=application/javascript outtype=application/javascript\

ExtFilterDefine jsminify: I defined a Filter name which I will be using in my htaccess

intype=application/javascript: This filter works on JavaScript files only as an application/javascript is their MIME Filetype

outtype=application/javascript: After working on this file, return it back as a JavaScript file

cmd=”/usr/bin/uglifyjs”: This is the command to execute on the file, it’s more accurate to enter the full path to the command, finding a full part to a command I type:

whereis uglifyjs


With no input file supplied, uglifyjs takes input from stdin and output to stdout. I saved the file and activate the config typing:

sudo a2enconf js-minify

Then reload apache2:

sudo service apache2 reload

Adding to htaccess

Set this to your htaccess and every JS file will be minified automatically when it passes Apache.

SetOutputFilter jsminify


About Author:

This article was written by Don Jajo from Nigeria. For any feedback or comment contact the author: [email protected]