Specifying Environment Variables (Or How To Use Env In Your Shebangs) With mod_fcgid

permanent link
Posted: September 162008

I recently switched from using a cluster of Mongrels on my Rails staging server to using FastCGI on Apache 2 with mod_fcgid installed. One thing that bugged me is that my dispatch.fcgi file would trigger the infamous Application Error: Rails application failed to start properly if I did not hardcode the path to my Ruby interpreter in the shebang of the script (e.g., the first line of the file appearing like: #!/opt/local/bin/ruby). I prefer to use the env program (e.g., the first line of the file appearing like #!/usr/bin/env ruby) so that my scripts are (fairly) portable across platforms where interpreters are located in different locations.

Today, I tried to resolve the situation as it was causing wasted time while testing/deploying. I finally found the solution. But not without spending a considerable amount of time heading down numerous paths toward dead ends.

I realized very quickly that the problem was that the environment variables mod_fcgid had access to, specifically $PATH, were not set to what they needed to be. So I tried a number of ways to set the $PATH only to fail several times before stumbling on the solution that should have been obvious.

The solution lies in your Apache 2 configuration. You need to add the following line wherever you happen to configure your mod_fcgid installation (I happen to include a file called httpd-fcgi.conf but most people could get away with doing this in their httpd.conf):

DefaultInitEnv PATH your path goes here

In fact, you can set any environment variable that you want your FastCGI script to have access to by using this method. I've seen several people have this shebang issue while using Ruby or Python scripts with FastCGI and there have been several workarounds posted that involve rewriting the shebang for different deployment targets. But I'd rather not do that if I don't have to. This solution works if you can modify your Apache 2 configuration and means you don't have to worry about an annoying detail like the shebang but simply get on with actual development.