Frodik Frodik - 1 month ago 13
Apache Configuration Question

How to force Apache to use manually pre-compressed gz file of CSS and JS files?

I have simple question. I have webdirectory

/css
and inside is file
style.css
. I have manually gzipped this file and saved it as
style.css.gz
. I want to save CPU cycles to not have CSS file compressed at each request. How do I configure Apache to look for this
.gz
file and serve it instead of compressing
.css
file over and over again ?

Note: I don't want Apache to create
.gz
file itself. In my scenario I have to create
.css.gz
file manually - using PHP on specific requests.

Answer

Some RewriteRule should handle that quite well.

In a Drupal configuration file I found:

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

This will make the job. You can put that either in a <Directory foo/> section or in a .htaccess file if you do not have access to apache configuration or if you want to slowdown your webserver.