Run python script as cgi under apache2 server

I was trying to set up a server with Pi 3, so I ran into this python CGI + Apache server path. Here is what I did and it works:

1. Install apache2 first, after the installation you should be able to see the default page with ‘localhost’ in your browser.

sudo apt-get install apache2

2. Enable mods in apache2 for cgi (the codes below showed two ways to do it)

sudo a2enmod cgid
cd /etc/apache2/mods-enabled
sudo ln -s /etc/apache2/mods-available/cgi.load

3. Modify the config file: /etc/apache2/conf-enabled/serve-cgi-bin.conf  to enable python code.

<Directory "usr/lib/cgi-bin">
             ... ...

             AddHandler cgi-script .py          # add this line (there is a blank between cgi-script and .py)
</Directory>

4. Notice that the default directory for cgi script is /usr/lib/cgi-bin/, so we will create a test file under this directory.

sudo nano /usr/lib/cgi-bin/pytest.py
#!/usr/bin/python

import cgi
import cgitb
cgitb.enable()

print 'Content-type: text/html\n\n'
print '
<h1>Python Script Test</h1>
'

5. Make the python file executable

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

6. Restart the apache2 service

sudo service apache2 restart

Now you should be able to see your test file output under ‘localhost/cgi-bin/pytest.py’ in your browser.

Note: I was having trouble restart the apache2 service after enable the cgi mods. So I actually reinstalled the apache2, it works after that. Here is how I reinstalled the apache2:

sudo apt-get --purge remove apache2
sudo apt-get autoremove
sudo apt-get install apache2

Hope this experience can help someone. Please let me know if there are anything need to be modified.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s