Enable python scripts in Apache

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

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”

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: