How to run Python web apps on CentOS using mod_wsgi for apache

1) Install Python

$ dnf (or yum) install python3

.

2) Install mod_wsgi for Apache

$ dnf install mod_wsgi

Check installation:

$ httpd -M | grep wsgi

The output should be smth like this:

wsgi_module (shared)

.

3) Configure Apache to load mod_wsgi

Firstly, locate the installed module path:

$ find / -type f -name "mod_wsgi.so"

Let’s assume it’s: /usr/lib64/httpd/modules/mod_wsgi.so

Put the next line at the of the apache configuration file (/etc/httpd/conf/httpd.conf)

LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.so

.

4) Modify virtual host file

<VirtualHost [IP:PORT]>
  ...
  <Directory {PATH}>
    ...
    <IfModule mod_wsgi.c>
      # Explicitly permit CGI execution:
      Options +ExecCGI

      # Handle .wsgi files with mod_wsgi
      <FilesMatch ".+\.wsgi$">
        SetHandler wsgi-script
      </FilesMatch>

      # Deny direct access to python files
      RedirectMatch 404 ".+\.py$"

      # Deny access to compiled binaries
      <FilesMatch ".+\.py(c|o)$">
        Order Deny,Allow
        Deny from all
      </FilesMatch>

      # Add a default Python index page
      DirectoryIndex index.wsgi
    </IfModule>
    ...
  </Directory>
</VirtualHost>

.

5) Additional Configuration

There might be applied some other directives such as WSGIDaemonProcess, WSGIDaemonProcess, WSGIScriptAlias, WSGIPythonPath, etc.

Especially WSGIPythonPath might be very useful as the specified path (or comma separated paths) as an import directory.

.

Note

After every configuration file update do not forget to test configuration file & restart the apache:

$ httpd -t && service httpd restart

Don’t forget to modify Virtual host file for SSL connection too, but as a best practice – to avoid code duplication, put the code above into a separate file, like _wsgi.conf and include it into the body of virtual hosts, like: Include /full/path/../_wsgi.conf

.

Bonus

index.wsgi file sample:

def application(environ,start_response):
    status = '200 OK'
    html = 'html content goes here'
    response_headers = [('Content-type','text/html')]
    start_response(status,response_headers)
    return [html]

.

@source:
https://modwsgi.readthedocs.io/en/master/
https://httpd.apache.org/docs/2.4/howto/cgi.html


Leave a Reply

Your email address will not be published. Required fields are marked *