Loading...
X

How to set up Python as a CGI module in Apache on Debian (Ubuntu, Linux Mint)

Setting up Python CGI for a single directory

Run the command to enable the CGI module:

sudo a2enmod cgi

Restart the web server for the changes to take effect:

sudo systemctl restart apache2

Create file /usr/lib/cgi-bin/test.py:

sudo gedit /usr/lib/cgi-bin/test.py

Copy the following content to this file:

#!/usr/bin/python3

print ("Content-type: text/html")
print ("")
print ("")
print ("<html><head>")
print ("")
print ("</head><body>")
print ("Hello.")
print ("</body></html>")

Make this file executable:

sudo chmod +x /usr/lib/cgi-bin/test.py

Open http://localhost/cgi-bin/test.py in a web browser

If everything is configured correctly, then you should see a line in the web browser

Hello.

Note: If instead of the /usr/lib/cgi-bin/ directory you want to use another folder for CGI scripts, then specify it in the /etc/apache2/conf-enabled/serve-cgi-bin.conf file.

Setting up Python CGI for the entire web server

Run the command to enable the CGI module:

sudo a2enmod cgi

Open the /etc/httpd/conf/httpd.conf file – the web server configuration file:

sudo gedit /etc/httpd/conf/httpd.conf

Find a group of lines there

<Directory /var/www/>
	Options Indexes FollowSymLinks
	AllowOverride None
	Require all granted
</Directory>

and replace them with

<Directory /var/www/>
	Options Indexes FollowSymLinks ExecCGI
	AllowOverride None
	Require all granted
</Directory>

ATTENTION: your set of options may be different.

Add the following line to the end of the file:

AddHandler cgi-script .cgi .py

Close the file.

Restart the web server for the changes to take effect:

sudo systemctl restart apache2

Create file /var/www/html/test.py:

sudo gedit /var/www/html/test.py

Copy the following content to this file:

#!/usr/bin/python3

print ("Content-type: text/html")
print ("")
print ("")
print ("<html><head>")
print ("")
print ("</head><body>")
print ("Hello.")
print ("</body></html>")

Make this file executable:

sudo chmod +x /var/www/html/test.py

Open http://localhost/test.py in a web browser

If everything is configured correctly, then you should see a line in the web browser

Hello.


Leave Your Observation

Your email address will not be published. Required fields are marked *