darksky
darksky

Reputation: 21019

How to use SSL with Flask

I am trying to set up Flask to run on SSL, along with redirecting all HTTP traffic to HTTPS.

I am currently using Apache as a web server, and it is serving traffic on port 80 HTTP properly. However, when I move the configuration under the port 80 VirtualHost into the port 443 and set up redirection for port 80, redirection works but Apache keeps showing the Apache Test Page, and is not serving the Flask application. The error logs are not showing anything useful. The only error I see is Directory index forbidden by Options directive: /var/www/html. I don't even use /var/www/html, and I know this is mostly a warning for older browsers.

Here is my Apache virtual host set up:

LoadModule wsgi_module modules/mod_wsgi.so
WSGISocketPrefix run/wsgi

NameVirtualHost *:80
<VirtualHost *:80>
        RewriteEngine On
        RewriteCond %{HTTPS} off
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

NameVirtualHost *:443
<VirtualHost *:443>
  SSLEngine on
  SSLEngine on
  SSLCertificateFile <<FILE PATH>>
  SSLCertificateKeyFile <<FILE PATH>>
  SSLCertificateChainFile <<FILE PATH>>
  SSLProtocol all -SSLv2
  SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW

  WSGIPassAuthorization On
  WSGIDaemonProcess api processes=4 threads=1
  WSGIProcessGroup api
  WSGIScriptAlias / /usr/local/app/api/current/conf/application.wsgi

  AddType text/html .py

  <Directory /usr/local/app/api/current/>
    Order deny,allow
    Allow from all
  </Directory>
</VirtualHost>

What is wrong with it? When I copy all the WSGI and Directory lines into port 80, and copy out 443, it works properly.

Upvotes: 3

Views: 13198

Answers (2)

sebisnow
sebisnow

Reputation: 2067

Checkout SSlify. Using this small flask extension all traffic gets redirected from HTTP to HTTPS.

All you have to do is to run the following when initializing your flask app:

from flask import Flask
from flask_sslify import SSLify

app = Flask(__name__)
sslify = SSLify(app)

Upvotes: 1

Paolo Casciello
Paolo Casciello

Reputation: 8202

This question belongs to Super User.

Btw it's not Flask related. You're missing DocumentRoot directive in your VirtualHost definition. So Apache uses the default /var/www/html.

Upvotes: 3

Related Questions