13 Nov 2007 mathrick   » (Journeyer)

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

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


Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!