Very Secure

A short guide for setting up apache with flask on gentoo.

1. Install apache.

emerge apache

2. Install mod_wsgi.

Before emerging mod_wsgi set your python targets to python2_7 by adding the following lines to /etc/portage/make.conf

PYTHON_TARGETS="python2_7"
PYTHON_SINGLE_TARGET="python2_7"
emerge --ask www-apache/mod_wsgi

3. Setup a group that has permissions for necessary files and directories.

groupadd www-data
usermod -a -G www-data apache
chown youruser:www-data necessaryfilesndirectories
chmod 0774 necessarydirectories1
chmod 0764 necessaryfiles

4. Add a virtual hosts file to /etc/apache2/vhosts.d. You may need to delete some other default hosts file in that directory that is competing for your port/ip address. Example vhosts file (modified from the example one in asciilifeform's logger) below:

Listen 80

WSGIPythonPath /home/youruser/pathtoyourwsgifile

<VirtualHost *:80>

    ServerName yourdomain.com

    ErrorLog /var/log/apache2/error.log
    CustomLog /var/log/apache2/access.log combined

    WSGIDaemonProcess yourbotuser user=youruser group=apache threads=16

    WSGIProcessGroup %{GLOBAL}

    WSGIScriptAlias / /home/youruser/yourcustompath/youruser.wsgi

    Alias /static/ /home/youruser/yourcustompath/static/

    <Directory /home/youruser/yourcustompath/static>
        Require all granted
    </Directory>

    <Directory /home/youruser/yourcustompath/>
    <Files yourwsgifile.wsgi>
        Require all granted
    </Files>
    </Directory>

</VirtualHost>

5. Create a wsgi file that looks like

#!/usr/bin/python

from yourflaskapp import app as application

6. Create a flask app yourflaskapp.py, example


from flask import Flask
from flask import request

PORT = 80
app = Flask(__name__)

@app.route('/')
def index():
    return "hello world"

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=PORT)

Bonus Tips:

7. Run apache commands via /etc/init.d/apache2, rather than just the global apache2 command.

8. Set apache's environment variables in /etc/conf.d/apache2.

  1. The execute bit is necessary to be able to search inside of a directory. []

Leave a Reply