Configure Apache + Passenger to serve static files from different directory

apache-2.2phusion-passengerruby-on-rails

I'm trying to setup Apache and Passenger to serve a Rails app. However, I also need it to serve static files from a directory other than /public and give precedence to these static files over anything in the Rails app.

The Rails app is in /home/user/apps/testapp and the static files in /home/user/public_html. For various reasons the static files cannot simply be moved to the Rails public folder. Also note that the root http://domain.com/ should be served by the index.html file in the public_html folder.

Here is the config I'm using:

<VirtualHost *:80>

  ServerName  domain.com

  DocumentRoot /home/user/apps/testapp/public

  RewriteEngine On

  RewriteCond /home/user/public_html/%{REQUEST_FILENAME} -f
  RewriteCond /home/user/public_html/%{REQUEST_FILENAME} -d
  RewriteRule ^/(.*)$ /home/user/public_html/$1 [L]
</VirtualHost>

This serves the Rails application fine but gives 404 for any static content from public_html. I have also tried a configuration that uses DocumentRoot /home/user/public_html but this doesn't serve the Rails app at all, presumably because Passenger doesn't know to process the request.

Interestingly, if I change the conditions to !-f and !-d and the rewrite rule to redirecto to another domain, it works as expected (e.g. http://domain.com/doesnt_exist gets redirected to http://otherdomain.com/doesnt_exist)

How can I configure Apache to serve static files like this, but allow all other requests to continue to Passenger?

Best Answer

Problem was a school boy mod_rewrite error - in order for the RewriteRule to be run both the RewriteCond statements above need to be satisfied, which of course they never will be. This was my fault for copying this from a negative condition test and not realising they would have to be separated. Although annoying that I need two RewriteRule statements, this works perfectly:

  RewriteCond /home/user/public_html%{REQUEST_URI} -f
  RewriteRule ^ /home/user/public_html%{REQUEST_URI} [L]
  RewriteCond /home/user/public_html%{REQUEST_URI} -d
  RewriteRule ^ /home/user/public_html%{REQUEST_URI} [L]