How to set up Python as a CGI module in Apache on Debian (Ubuntu, Linux Mint)
May 21, 2023
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.
Related articles:
- How to install Python as a CGI module in Apache on Linux (100%)
- How to set up Python as a CGI module in Apache on Arch Linux (Manjaro, BlackArch) (83%)
- How to get data from a web page using GET and POST methods in a Python script (83%)
- Error “Cannot load modules/libphp7.so” (SOLVED) (72.8%)
- How to set up HTTPS on Apache in Debian, Ubuntu, Linux Mint, Kali Linux (72.8%)
- How to change the interface (menu) language of VLC media player in Linux (RANDOM - 50%)