Add Python support to apache2 in Ubuntu

Some host providers only let you run CGI scripts in a certain directory, often named cgi-bin. In this case all you have to do to run the script is to call it like this:


The script will have to be made executable by “others”. Give it a 755 permission or check the executable boxes if there is a graphical FTP interface.

Some hosts let you run CGI scripts in any directory. In some of these hosts you don’t have to do anything to configure the directories. In others you will have to add these lines to a file named .htaccess in the directory you want to run CGI scripts from:

Options +ExecCGI
AddHandler cgi-script .py

If the file does not exist create it. All directories below a directory with a .htaccess file will inherit the configurations. So if you want to be able to run CGI scripts from all directories create this file in the document root.

If you are using your own server then probably you won’t need to do anything to run a CGI script at the cgi-bin directory. Just make sure there is a line like the next in httpd.conf and that it is not commented. The trailing slashs are required.

ScriptAlias /cgi-bin/ "/path/to/cgi-bin/directory/"

If you are using the line above and want html files to be handled correctly in the cgi-bin directory add the next to httpd.conf. No trailing slash.

<Directory /path/to/cgi-bin/directory>
   AddHandler default-handler .html .htm

To run a script saved at the root:


If it was saved in some directory:


If your desktop is the server then execute it like this:


In Windows, sometimes Apache will listen on port 8080. In this case the above address will be written with the port:


Make sure all text files you upload to the server are uploaded as text (not binary), specially if you are in Windows, otherwise you will have problems.


Note: Following solution is another one, but did not work for all my scripts 😦

Install apache2: sudo apt-get install apache2

Default web root directory is under /var/www

Install mod_python: sudo apt-get install libapache2-mod-python

Edit configuration: sudo vim  /etc/apache2/sites-available/default

Add the three lines AddHandler mod_python .pyPythonHandler mod_python.publisher, and PythonDebug On to the end of section “<Directory /var/www/>”

Restart apache service:  sudo /etc/init.d/apache2 restart

Create test file: sudo vi /var/www/

def index(req):
  return "Test successful";

Open web browser and input : http://localhost/