Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Install Apache & Python on Ubuntu 16.04 LTS

We’ll be using a freshly installed server with Ubuntu Server 16.04, Ubuntu Desktop should also work.

By default Ubuntu 16.04 ships with Python 3 but you won’t be able to call it if you issue the following at shell:

python --version

You’ll instead be greeted by this error message:

The program 'python' can be found in the following packages:
* python-minimal
* python 3

Try: sudo apt install 'package'

Instead if you issue the following, you’ll get the proper version:

python3 --version
Python 3.5.2

So to get the OS to call python when we just type python at the terminal we need to do the following:

sudo ln -s /usr/bin/python3 /usr/bin/python

Note: If you have an older version of python installed you will need to first remove the link to it and then create the new one, here’s how:

sudo rm /usr/bin/python

Moving on, time to install the package manager for python, pip

sudo apt-get install python3-pip

Now to install Apache, 

sudo apt-get install apache2

Create a directory to hold the python files

sudo mkdir /var/www/pythontest

Next, to register python with apache we must disable multithreading processes

sudo a2dismod mpm_event

Now to give apache permission to run the scripts

sudo a2enmod mpm_prefork cgi

Next, modify apache’s configuration to set Python files as runnable and allow them to be executed

sudo vi /etc/apache2/sites-enabled/000-default.conf

Add the following block right under the Virtualhost start declaration, usually right after the first line:

<Directory /var/www/pythontest>
    Options +ExecCGI
    DirectoryIndex index.py
</Directory>
AddHandler cgi-script .py

Next, change Apache’s default document root to your newly created pythontest directory, look for the word DocumentRoot in the same config and change to:

DocumentRoot /var/www/pythontest

Restart Apache:

sudo service apache2 restart

Now it’s time to test things, create a index.py file in the set directory and add the sample Hello World script:

cd /var/www/pythontest
vi index.py

Add the following:

#!/usr/bin/python
print()
print ("Hello World!");

Save, and hit your server’s IP in your browser and you should see the “Hello World!” text.

Note: Python3 requires updated syntax to function properly, you may see HTTP 500 Internal Server errors with the old syntax