Your Linux Data Center Experts

How to set up Rails with mod_fcgi

By  Sean Reifschneider Date October 2, 2005

The current (October 2005) recommendations for running rails seem to be either to use Apache 1.3 with Fast CGI, or to use Lighttpd with FastCGI. Most documents either say that Apache 2.x with mod_fcgid, the Apache 2.x replacement for FastCGI, AKA fcgi and fcgid, does not work or they only go so far as to say that it's rumored to work. Not entirely helpful.

I'd be more interested in trying lighttpd if it weren't for the fact that Debian Testing doesn't have it. They'll have to get on it. In the mean time, since I already have Apache2 running on this test site, I decided to figure out Rails+mod_fcgid.

You will almost certainly need the Ruby "fcgi" module and Apache2 mod_fcgid modules. In Debian Testing these are packages named "libapache2-mod-fcgid", and "libfcgi-ruby1.8".

Next, you will need to configure your Apache virtual site. In my case, I'm using a name-based virtual, with my Rails site under /home/httpd. My VirtualHost directive looks like:



   DocumentRoot /home/httpd/WWW.EXAMPLE.CA/MYAPPNAME/public/
   #  Yes, referrer is mis-spelled, this is for legacy reasons
   CustomLog /var/log/apache2/referer_log combined

   #  Note that you can't put this in the .htaccess
   DefaultInitEnv RAILS_ENV production
   <Directory /home/httpd/WWW.EXAMPLE.CA/MYAPPNAME/public/>
      Options ExecCGI +FollowSymLinks
      AllowOverride All
      order allow,deny
      allow from all

Strings in all caps will likely need to be changed, but so will "/home/httpd", depending on where you put your applications.

Next you need to modify the "MYAPPNAME/public/.htaccess" file so that the "AddHandler fcgid-script .fcgi" at the top, and has a RewriteRule for "dispatch.fcgi". Note that the default .htaccess file includes lines for "fastcgi-script" and "dispatch.cgi", make sure you don't mistake "cgi" for "fcgi", it can be easy to do. Here are some excerpts from my .htaccess file:

RewriteEngine On
# General Apache options
#COMMENTED OUT#AddHandler fastcgi-script .fcgi
#COMMENTED OUT#AddHandler cgi-script .cgi
AddHandler fcgid-script .fcgi
Options +FollowSymLinks +ExecCGI
RewriteRule ^$ index.html [QSA]
RewriteRule ^([^.]+)$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
#COMMENTED OUT#RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

That's pretty much it. You will, on Debian, have to make sure that you have the "fcgid.*" and "rewrite.*" files linked from "/etc/apache2/mods-available" into "mods-enabled" or the server won't be able to find the modules for fcgid and rewrite -- both of which are required:

cd /etc/apache2/mods-enabled
ln -s ../mods-available/fcgid.* .
ln -s ../mods-available/rewrite.* .

Of course, once you make these changes, you'll need to restart Apache for the changes to take effect.

comments powered by Disqus