Run a simple Python CGI on Apache Web Server
Published 6 months ago: July 20, 2020
A how-to on running a simple Python CGI script on an Apache HTTP 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
- Configure Apache's configuration file
- Open the config file in any editor. Usually exists in
/etc/apache2/apache2.conf
. Example:sudo nano /etc/apache2/apache2.conf
- 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.
- Open the config file in any editor. Usually exists in
- Put the Python script in cgi-bin (usually
/var/www/html/cgi-bin/
)- Example:
sudo cp /path/to/script/your_script.py /var/www/html/cgi-bin/your_script.py
- Example:
- Make sure Apache has permission to execute the file
chmod +x your_script.py