How to execute Python CGI Script on Apache Server?

Python CGI (Common Gateway Interface) scripts allow you to run Python programs on a web server to generate dynamic web content. By default, Apache doesn't execute Python scripts, so you need to configure it properly.

Prerequisites

Before configuring Apache for Python CGI, ensure you have:

  • Apache web server installed
  • Python installed on your system
  • Access to Apache configuration files

Step 1: Configure Apache httpd.conf File

Open the Apache configuration file httpd.conf (usually located in /etc/apache2/ or /etc/httpd/conf/) and add the following configurations:

# Enable CGI module
LoadModule cgi_module modules/mod_cgi.so

# Add handler for Python scripts
AddHandler cgi-script .py

# Configure CGI directory
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options +ExecCGI
    Require all granted
</Directory>

# Set script alias
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

Step 2: Create a Python CGI Script

Create a simple Python CGI script in your cgi-bin directory:

#!/usr/bin/python3

import cgi
import cgitb

# Enable CGI error reporting
cgitb.enable()

# Print Content-Type header
print("Content-Type: text/html\n")

# Print HTML content
print("<!DOCTYPE html>")
print("<html>")
print("<head><title>Python CGI Test</title></head>")
print("<body>")
print("<h1>Hello from Python CGI!</h1>")
print("<p>This script is running on Apache server.</p>")
print("</body>")
print("</html>")

Step 3: Set File Permissions

Make your Python script executable by setting proper permissions:

chmod +x /var/www/cgi-bin/test.py
chown www-data:www-data /var/www/cgi-bin/test.py

Step 4: Restart Apache Server

After making configuration changes, restart the Apache server:

# On Ubuntu/Debian
sudo systemctl restart apache2

# On CentOS/RHEL
sudo systemctl restart httpd

# Alternative method
sudo service apache2 restart

Testing Your CGI Script

Access your Python CGI script through a web browser using the URL:

http://your-domain.com/cgi-bin/test.py

Common Issues and Solutions

Issue Solution
500 Internal Server Error Check file permissions and shebang line
Script downloads instead of executing Verify AddHandler configuration
Permission denied Set executable permissions with chmod +x

Security Considerations

When using CGI scripts, consider these security practices:

  • Validate all user inputs to prevent injection attacks
  • Use cgitb.enable() only during development
  • Restrict CGI directory access appropriately
  • Keep Python and Apache updated

Conclusion

Configuring Apache to run Python CGI scripts requires enabling the CGI module, adding the Python handler, and setting proper permissions. Always restart Apache after configuration changes and ensure your scripts have the correct shebang line and executable permissions.

Updated on: 2026-03-24T20:01:34+05:30

629 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements