This is a card in Dave's Virtual Box of Cards.

Local dynamic viewing of static website via CGI wrapper

Page created: 2023-06-21

Back to web-cgi

I’m really excited about this: My static website can be viewed dynamically on my local "intranet" web server for fast previewing while I edit a page.

All I have to do is save the page source file (the file extension happens to be .txt but you can think of it as .md) and refresh the browser. The page is generated on the fly just like any dynamic site.

There are three parts to making this work:

httpd.conf (Apache config)

The hardest part is always getting the web server incantations just right. Here’s mine for Apache:

<Directory "/home/dave/proj/zigdoc/">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
    Options +ExecCGI
</Directory>
Alias /zigdoc /home/dave/proj/zigdoc/output
RewriteEngine On
RewriteRule /zigdoc/(.*).html /home/dave/proj/zigdoc/cgi.sh [env=PAGE:$1,H=cgi-script]

The key here is the RewriteRule:

  • /zigdoc/(.*).html matches a request for a .html page in a particular directory.

  • The (.*) part of the above regular expression captures the file name minus the .html extension.

  • /home/dave/proj/zigdoc/cgi.sh rewrites the request to point to the CGI wrapper script.

  • env=PAGE:$1 sets an environment variable to the value of the captured file name from the regular expression.

  • H=cgi-script sets the "handler" for this match to cgi-script, so the re-written request will be treated as a CGI request

CGI wrapper shell script

Here’s the whole thing. As you can see, it just writes the minimum required HTTP header and then calls my static site generator program, zigdoc, with the $PAGE from the environment variable set in the Apache RewriteRule above.

#!/bin/bash

echo "Content-type: text/html"
echo ""

infile=pages/$PAGE.txt

./zigdoc $infile

exit 0

Static page generator

Mine happens to be written in Zig, but that’s not important. What’s important is that it writes output to STDOUT rather than a disk file.

The converted content (HTML generated from the source .txt file) is captured by the web server and returned as the page content.

All hail the flexibility of file redirection and stdout!