Want to run Python from Apache 2.4, this is what I did to get it working. For this exercise I am creating a web hook script and want to run them from the custom folder “/srv/www/webhooks/”.
Apache config changes
First backup and then open up “/etc/httpd/conf/httpd.conf” in your favorite editor..
Search for “#AddHandler cgi-script .cgi” and change this to:
AddHandler cgi-script .cgi .py
Search for “ScriptAlias /cgi-bin/”. This will return a list of folders which run cgi scripts, typically something like:
ScriptAlias /cgi-bin/ “/var/www/cgi-bin/”
Because we want to run from a different folder I needed to add a new entry directly below:
ScriptAlias /webhooks/ “/srv/www/webhooks/”
Next look for a line “<Directory “/var/www/cgi-bin”>”. This defines the settings of the cgi-bin folder. At the end it has a “</Directory>”. Below this add a section for the web hooks folder:
# # Script alias folder for web hook scripts # <Directory "/srv/www/webhooks"> AllowOverride None Options None Require all granted </Directory>
Now restart Apache to enable your changes. For RedHat use:
systemctl restart httpd.service
Create the Python script
Create a folder for your scripts, in my case my web files are under “/srv/www” so create a subfolder “webhooks”:
mkdir -p /srv/www/webhooks chown apache.apache /srv/www/webhooks chmod 2770 /srv/www/webhooks
Create a sample Python file “/srv/www/webhooks/test.py”
#!/usr/bin/env python import cgi; import cgitb;cgitb.enable() # Print headers print "Content-Type: text/html" print "" # Print page print("<html>") print("<title>Webhook Test Page</title>") print("<body>Test webhook page by Zoyinc.</body>") print("</html>")
Set the correct permissions:
chmod 770 /srv/www/webhooks/test.py
Go to your favorite browser and see if it works, the url for me is http://www.zoyinc.com/webhooks/test.py
You should see the following:
Problems
Running a virtual host
If you are running in a virtual host you may need to add the details there:
<VirtualHost *:80> ServerAdmin studentsonline@zoyinc.com DocumentRoot /srv/www/studentsonline ServerName studentsonline.zoyinc.com ErrorLog logs/studentsonline.zoyinc.com-error_log CustomLog logs/studentsonline.zoyinc.com-access_log combined DirectoryIndex "Students OnlineM.html" ScriptAlias /studentsonline/ "/srv/www/studentsonline/" # # Script alias folder for students online scripts # <Directory "/srv/www/studentsonline"> AllowOverride None Options None Require all granted AddHandler cgi-script .py </Directory> </VirtualHost>
Logs
It is good to tail the apache log, so something like:
tail -f /var/log/httpd/www.zoyinc.com-error_log
Remember Apache has a different log for each virtual host – which is why the above is named www.zoyinc.com.