Run a simple Python CGI on Apache Web Server

Prerequisites

  • Python 3.x

First things first

First, save the script below to a file.

#!/usr/bin/env python3
import cgi
from string import Template

# enable debugging
import cgitb
cgitb.enable()

print('Content-Type: text/html; charset=utf-8\n')

Then

  1. Configure Apache's configuration file
  2. Open the config file in any editor. Usually exists in /etc/apache2/apache2.conf. Example: sudo nano /etc/apache2/apache2.conf
  3. Put this in at the end: ScriptAlias /myscript/ "/var/www/html/cgi-bin/your_script.py". 'myscript' is the URL you want the script at.
  4. Put the Python script in cgi-bin (usually /var/www/html/cgi-bin/)
  5. Example: sudo cp /path/to/script/your_script.py /var/www/html/cgi-bin/your_script.py
  6. Make sure Apache has permission to execute the file chmod +x your_script.py