How to configure Apache for Python CGI Programming?

Configure Apache Web server for CGI

To get your server run CGI scripts properly, you have to configure your Web server. We will discuss how to configure your Apache web server to run CGI scripts.

Using ScriptAlias

You may set a directory as ScriptAlias Directive (options for configuring Apache). This way, Apache understands that all the files residing within that directory are CGI scripts. This may be the most simple way to run CGI Scripts on Apache. A typical ScriptAlias line looks like following in httpd.conf file of your Apache web server.

ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/

So, search ScriptAlias in your httpd.conf file and uncomment the line (remove preceding #) if you want to keep all your CGI files in the default directory specified by Apache. But this may not meet your requirement always. So, we will look some other options also for running Python as CGI.

Running CGI from a particular directory other than default one

You may use the following to prepare a particular directory to run CGI files.

<Directory /usr/local/apache2/htdocs/somedir>Options +ExecCGI</Directory>

Where 'somedir' is the directory of your preference.

If you use the above configuration. then you have to specify the following also to tell server extensions of the CGI files you winch to run.

AddHandler cgi-script .cgi .pl

So, the above tells Apache to run files with .cgi and .pl extensions as CGI

User Directories

If you want to run CGI files from user's directory, then you may use the following −

<Directory /home/*/public_html>
Options +ExecCGI
AddHandler cgi-script .cgi

The above says Apache to run all files with .cgi extension present within user's directory as CGI.

Again, if you wish to run all files placed within user's directory as CGI, then you may use the following −

<Directory /home/*/public_html/cg-bin>
Options +ExecCGI
SetHandler cgi-script
Using .htaccess

If you don't have access to your httpd.conf file, you may use a .htaccess file to run CGI scripts. To use files with certain extensions as CGI, configure you .htaccess file as following −

Options +ExecCGI
AddHandler cgi-script cgi pl

If you would like to run all files residing within a directory as CGI, you may use the following −

Options +ExecCGI
SetHandler cgi-script

Updated on: 16-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started