12

In Nginx there is try_files, a config directive that "checks for the existence of files in order, and returns the first file that is found". I find it very neat to do this

location ~* \.(gif|jpe?g|css|js)$ {
    try_files $uri 404;
}

which is a safe way of directly serving static files, without bothering the web frameworks. How can I do the same thing in Apache?

migrated from unix.stackexchange.com Jul 15 '11 at 16:45

This question came from our site for users of Linux, FreeBSD and other Un*x-like operating systems.

  • 1
    What was the solution you went for? The selected answer does not really meet my use case. – panepeter Mar 13 '18 at 17:27
9

I commonly see this done with mod_rewrite:

 RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
 RewriteRule ^/(.*)$ balancer://app_cluster%{REQUEST_URI} [P,QSA,L]

It means "If a file does not exist on the file system, then proxy it through my mod_proxy_balancer cluster." Otherwise, if the file exists on the file system, it is simply served up by Apache relative to the defined DocumentRoot in your virtualhost.

But that's not my favorite way, mostly because it would require a stat system call per request.

With mod_proxy, you can use ProxyPassMatch if you have a new enough version of Apache (see documentation). Such as:

ProxyPassMatch \.(gif|jpe?g|css|js)$ !

Which uses the ! to indicate Apache should not proxy requests matching that regular expression.

If you are using an older version of Apache, you will have the ProxyPass directive available to you, but it only matches URI prefixes (this is my current preferred method):

ProxyPass /images !
ProxyPass /stylesheets !

Of course, if you must do regular expression matching as you mentioned above, then you can simply modify the mod_rewrite rule I posted at the top to negate a match against the %{REQUEST_URI}.

Hope that helps!

  • 2
    I think the "bad" way is more similar to try_files, because it checks for the existence of the file. There doesn't seem to be a way to do it for ProxyPass though. – phunehehe Nov 12 '13 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.