CGI programming with THTTPD

Published: 2010-02-02 by Pradeep Gowda.
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
  $ 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.


Let’s test the setup.

  $ cat - > htdocs/test.html
   <h1>Hello thttpd</h1>
  $ ./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/>'

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.