Lately, I had to quickly set up a small CGI running example. Here's how to do it.
1. Local Web root folder
If it does not exist, create a ~/Sites
and a ~/Sites/cgi-bin
folder.
Create a new file /etc/apache2/your-username.conf
containing the following:
<Directory "/Users/your-username/Sites/cgi-bin/">
AllowOverride None
Options ExecCGI
AddHandler cgi-script .cgi .pl .tcl .py
Order allow,deny
Allow from all
</Directory>
and set permissions to 644
.
2. Apache extensions
Edit /etc/apache2/httpd.conf
and de-comment the following modules:
LoadModule authz_core_module libexec/apache2/mod_authz_core.so
LoadModule authz_host_module libexec/apache2/mod_authz_host.so
LoadModule userdir_module libexec/apache2/mod_userdir.so
You need also to uncomment:
Include /private/etc/apache2/extra/httpd-userdir.conf
Finaly, edit /etc/apache2/extra/httpd-userdir.conf
and uncomment
Include /private/etc/apache2/users/*.conf
3. Adding a CGI
Add an index.html
in ~/Sites
, e.g.:
<!DOCTYPE html>
<html>
<head>
<title>CGI showcase</title>
</head>
<body>
<form action="cgi-bin/greeting.py" method="POST">
<fieldset>
<legend>Personal information:</legend>
<label for="firstname">First name:
<input type="text" name="firstname" placeholder="Guybrush" required="true"><br>
<label for="lastname">Last name:
<input type="text" name="lastname" placeholder="Threepwood" required="true">
<br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
Then, let us add a simple CGI script in Python as ~/Sites/cgi-bin/greeting.py
:
#!/usr/bin/python
import cgi
import os
def main():
form = cgi.FieldStorage()
print "Content-type: text/html"
print
print "<html><head>"
print "<title> Hi! </title>"
print "</head><body>"
print "Hi %s %s" % (form.getvalue("firstname"), form.getvalue("lastname"))
# print "REQUEST_METHOD: %s" % os.environ['REQUEST_METHOD']
print "</body></html>"
return 0
if __name__ == '__main__':
main()
4. Lunching Apache
The only thing left is to start Apache:
sudo apachectl start
The Web app should be available at
http://localhost/~your-username