Install Apache Python mod_wsgi

Posted under » Apache » Python on 17 April 2021

When you install LAMP, php is installed with apache and mysql but in for django you have to install them individually.

First you need to install Python Apache Mod_wsgi. The mod_wsgi is an Apache module used to serve Python scripts over HTTP.

$ sudo apt install libapache2-mod-wsgi

For python 3 you need to do this instead.

$ sudo apt install libapache2-mod-wsgi-py3

Restart Apache. Now create a file on webfolder 'test_wsgi_script.py'.

def application(environ,start_response):
    status = '200 OK'
    html = '\n' \
           '\n' \
           'Alhamdulillah, mod_wsgi is working\n' \
           '\n' \
           '\n'
    response_header = [('Content-type','text/html')]
    start_response(status,response_header)
    return [html]

Now create a configuration file eg. /etc/apache2/conf-available/mod-wsgi.conf with the following contents.

WSGIScriptAlias /test_wsgi /var/www/scripts/test_wsgi_script.py

Enable it.

$ sudo a2enconf mod-wsgi
$ sudo systemctl restart apache2

The Python script is ready to serve over Apache. You can test the script by accessing the URL http://fi3fi.com/test_wsgi in a web browser.

You will notice that this applies system wide and may not be ideal if you have several virtual sites or environment. So lets do for a specific vhost.

<VirtualHost *:80>
ServerName fi3fi.com
 ServerAdmin webmaster@localhost
   WSGIScriptAlias /test_wsgi /var/www/scripts/test_wsgi_script.py
        DocumentRoot /var/www/scripts/

        Options Indexes FollowSymLinks MultiViews

        ErrorLog ${APACHE_LOG_DIR}/error-fi3fi.log
        CustomLog ${APACHE_LOG_DIR}/access-fi3fi.log combined
</VirtualHost>

If you want to use django, read this

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS