Apache – Using Minified JavaScript If Available

I am currently working on a totally new layout and was recently trying to ensure that if the minified version of a JS file existed on my site, it would be used instead of the normal version. Thusly, I decided to use Apache’s .htaccess file to create a rewrite rule which would test to see if the requested .js file has a corresponding .min.js file in the same directory. If it is found, the minified version will be returned to the client instead of the normal version. The following is a portion of my .htaccess file in my document root:

RewriteBase /
RewriteCond %{REQUEST_URI} ^(.+)\.js$
RewriteCond %{DOCUMENT_ROOT}/%1.min.js -f
RewriteRule ^(.+)\.js$ %1.min.js [L]

The biggest issue that you have to worry about if you decide to use this approach is the fact that if you update the normal .js file, you need to also update the corresponding .min.js. Have fun! 8)

Leave a Reply

Your email address will not be published. Required fields are marked *