John D Wells
John D Wells

Reputation: 198

mod_rewrite help when .htaccess is located in subdirectory

I have a simple rewrite rule that checks if a *.gz version of the requesting file exists, and if so returns that file to the browser (it's based around this technique for serving compressed CSS & JS: https://blog.jcoglan.com/2007/05/02/compress-javascript-and-css-without-touching-your-application-code/).

Assume that my CSS & JS reside in a /cache subdirectory of my site, e.g.:

http://domain.com/cache/app.css
http://domain.com/cache/app.css.gz
http://domain.com/cache/app.js
http://domain.com/cache/app.js.gz

When the following directives are placed within the .htaccess file at webroot, everything works as expected:

AddEncoding gzip .gz
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{HTTP_USER_AGENT} !Safari
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)$ $1.gz [QSA,L]

However I'd prefer to place these rules within a separate .htaccess file that sits within that /cache directory. But pasted as-is, the rules no longer work. From what I can tell, the last RewriteCond is failing, e.g. the condition which checks if the requested filename exists.

I've tried adding RewriteBase /cache/ but that didn't seem to work. I've removed my webroot .htaccess in case there was another directive there that was conflicting. I've also tried changing the RewriteRule to:

RewriteRule ^(.*)$ /cache/$1.gz [QSA,L]

And while I think that might be correct in the end, it still doesn't work - like I said because from what I can tell it's the RewriteCond which is failing.

So I'm stumped! Any help?

Upvotes: 2

Views: 181

Answers (1)

anubhava
anubhava

Reputation: 785038

Following rule should work from /cache/.htaccess:

AddEncoding gzip .gz
RewriteEngine On

# Determine the RewriteBase automatically/dynamically
RewriteCond $0#%{REQUEST_URI} ^([^#]*)#(.*)\1$
RewriteRule ^.*$ - [E=BASE:%2]

RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{HTTP_USER_AGENT} !Safari
RewriteCond %{DOCUMENT_ROOT}%{ENV:BASE}/$1\.gz -f [NC]
RewriteRule ^(.+?)/?$ $1.gz [L]

Upvotes: 1

Related Questions