CGI programming with THTTPD

THTTPD is a fast, light-weight web server.

Created: by Pradeep Gowda Updated: May 22, 2020 Tagged: code · cgi · thttpd

thttpd is a small, fast and robust HTTP server that weighs in at less than 100KB of executable.

thttpd can make a fine web server for lean hardware (eg: single board computers).

Here, I am trying to serve a CGI application using tHTTPd.

Install thttpd

  $ cd
  $ wget http://acme.com/software/thttpd/thttpd-2.25b.tar.gz
  $ tar -zxvf thttpd-2.25b-tar.gz
  $ mv thttpd-2.25b thttpd
  $ rm thttpd-2.25b.tar.gz
  $ cd thttpd
  $ make

Run thttpd

  $ sudo ./thttpd

By default thttpd runs on port 80, for which you need to be root. Let’s kill the process and use a higher port, which is accessible to non-super users.

  $ sudo killall -9 thttpd
  $ ./thttpd -p 8000

Configuring thttpd

Let’s copy the supplied example config file to the current directory and modify it to suite our requirement.

 $ cp contrib/redhat-rpm/thttpd.conf .
 $ mkdir htdocs
 $ mkdir htdocs/cgi-bin
 $ mkdir log
 $ mkdir run

Note: I’m taking a few liberties in setting up the server. My intention here is to get to cgi programming. Check thttpd docs for safer alternatives, including chrooting thttpd.


dir=/home/pradeep/thttpd/htdocs
user=pradeep
logfile=/home/pradeep/thttpd/log/thttpd.log
pidfile=/home/pradeep/thttpd/run/thttpd.pid
port=8000
host=0.0.0.0
charset=utf-8
cgipat=**.cgi

Let’s test the setup.

  $ cat - > htdocs/test.html
   <h1>Hello thttpd</h1>
   ^D
  $ ./thttpd -C thttpd.conf

Visiting http://localhost:8000/ should show you the newly created page.

Creating a CGI Application

  $ cat - > htdocs/cgi-bin/hello.cgi
#!/usr/bin/env python
print "Content-Type: text/html"     # HTML is following
print                               # blank line, end of headers
print "<TITLE>CGI script output</TITLE>"
print "<H1>This is my first CGI script</H1>"
print "Hello, world! <br/>"
for i in range(10):
    print i, '<br/>'
print 'Just to show that some stuff is "dynamically" generated server side<br/>'
^D

The above code is directly out of Python CGI library doc.

  $ chmod +x htdocs/cgi-bin/hello.cgi

Restart the server and visit http://localhost:8000/cgi-bin/hello.cgi to see this simple CGI script in action.