Running Ruby as a CGI Script with Apache on OS X (Leopard)
It took me a couple different documents to get me running a Ruby script on the built-in Apache webserver that comes with OS X, so I figured I'd document the steps.
First of all you have to have the web server running, but I'm going to assume that's already setup.
The out-of-the-box Apache config file (/etc/apache2/httpd.conf
) is setup to alias the webroot path /cgi-bin/
into the directory /Library/WebServer/CGI-Executables/
. Write a little Ruby script and drop it in that directory. It needs to be executable by all (chmod a+x hello_world.cgi
). Make sure to include the script declaration statement to let the CGI process know how to execute it. Here is an example (hello_world.cgi):
#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new('html3')
cgi.out do
cgi.html do
cgi.body do
cgi.p { 'Hello World' }
end
end
end
I used Ruby's CGI library because it removes a lot of boilerplate crap but more importantly because when I wrote a plain script that outputted its own HTTP Headers, I kept getting script errors (500s). The Apache log file told me there was something wrong with my headers, but I couldn't for the life of me figure out what was wrong with it.
OK we've got our Hello World Ruby script that is in /Library/WebSite/CGI-Executables/
so now all we have to do is edit the Apache config file (/etc/apache2/httpd.conf
) to setup the execution of .cgi
files. So edit the config file by uncommenting the following line: AddHandler cgi-script .cgi
. In my file it was on line #391, but yours may be different. Note that this line will be located in a block that is tagged like: IfModule mime_module
.
Now just make sure your CGI module is loaded by uncommenting the following line: LoadModule cgi_module libexec/apache2/mod_cgi.so
. Mine was on line #102 but again, your config file may be different.
That's all you have to do in the config file, so save your changes (need sudo
) and then restart Apache: sudo apachectl restart
Hit your script in the browser at the path: http://localhost/cgi-bin/hello_world.cgi
and it should work.
Now that you've got it working, you can tweak your apache config a bit more to add directories in your home Sites directory to be CGI-executable so you don't have to save everything in the obscure /Library/WebSite/CGI-Executables/
path. You can also add some other extension types besides .cgi
if you want, but I prefer to leave it at the default extension because it doesn't reveal to the client what type of code is being executed.
If you're the only one that uses that webserver, then I recommend changing the DocumentRoot
directory to be your Sites directory. This setting is on line #163 in my config file.
Comments
- If not now then when? » Running Ruby as a CGI Script with Apache … Scripts Rss on October 21, 2009, at 07:49 AM