Routing complete Apache traffic to a CGI handler

Following up on my CGI-Lisp work, here’s a short recipe on how to route the entire Apache traffic to a CGI handler. This is not trivial because of a few problems that need solving:

  1. mod_actions will fall into infinite loop if you try to associate a handler with <Location /> (as will mod_rewrite if you attempt to rewrite /.*)
  2. mod_rewrite will not execute CGI scripts by default
  3. mod_rewrite only serves physical paths under DocumentRoot (and it’s good practice not to have /cgi-bin/ under DocumentRoot)

These can be all solved, but require some searching and reading into the meaning of various options, so I’m posting a ready solution here:

<VirtualHost *:80>
    ...
    DocumentRoot /var/www/
    ...

    RewriteEngine On
    # PT means "passthrough" and will allow mod_rewritten URLs to be matched by
    # virtual locations, not just physical paths
    # T= specifies mime-type to ensure the CGI handler will be executed
    # sock.cgi is the handler we want to handle the entire traffic
    RewriteRule ^/(.*) /cgi-bin/sock.cgi/$1 [PT,T=application/x-httpd-cgi]

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        #Add whatever options you normally use for your /cgi-bin/
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>

As an added bonus, it seems that the REQUEST_URI sent is the URL before rewriting, so you don’t have to do anything special to filter out /cgi-bin/sock.cgi from it.