The first step is to update your server:
sudo apt-get update
Then install your Apache2 web server:
sudo apt-get install apache2
Create your CGI directory
This is where all script you wish to execute will go
sudo mkdir /var/www/cgi-bin
The next step tells Apache which directories it can execute in and how to handle a .py file when it sees one. With an editor open /etc/apache2/sites-available/default
sudo vi /etc/apache2/sites-available/default
Inside is a long list of configurations. We want to look at the block of text which should start around line 16. It looks like this:
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin/">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
Change it to look like this:
(be sure to copy this carefully)
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
<Directory "/var/www/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
AddHandler cgi-script .py
AddHandler default-handler .html .htm
</Directory>
Now save and exit.
Now it's time to make your homepage. Apache will automatically display /var/www /index.html, so we will use this file to make our home page.
Open the file with:
sudo vi /var/www/index.html
Delete everything inside.
Replace it with:
Now that we have that, we need to make a script to parse it input and return a response.
Go to your cgi-bin directory and with an editor create serverscript.py:
cd /var/www/cgi-bin
sudo vi serverscript.py
Here is the code we will be using for some sample tasks:
!/usr/bin/python
import cgi
import cgitb
cgitb.enable()
Retrieve form fields
form = cgi.FieldStorage() # Get POST data
fname = form.getfirst("fname") # Pull fname field data
lname = form.getfirst("lname") # Pull lname field data
secret = form.getfirst("secretsquirrel") # Pull secretsquirrel field from POST data
Begin HTML generation
print "Content-Type: text/html; charset=UTF-8" # Print headers
print "" # Signal end of headers
HTML is pushed to the page with print
To save time you can use ''' to open and close a print
statement for block printing
print '''
'''
print "First name:",fname
print "
"
print "Last name:",lname
print "
"
print "Whole name:",fname+" "+lname
print "
"
print "The secret was:",secret
print '''
'''
Now allow the script to be executable:
sudo chmod +x serverscript.py
Restart apache2 so that config file changes take effect:
(This does not need to be done when changing site content, only apache2 config files)
sudo /etc/init.d/apache2 restart