Search code examples
pythonnginxflaskgunicorncentos8

Flask talisman not working and redirects to https://localhost:8000


I have been running flask-talisman on my development server and everything checks out fine. Yet, with the same code and requirements installed on my dedicated server for production (Almalinux), just adding Talisman(app) after app = Flask(__name__) results in the webpage not loading with a redirection to https://localhost:8000. The error message that I precisely get on my browser after typing in the domain is:

This site can't be reached - localhost refused to connect

I am running Nginx 1.14.1 with gunicorn 20.1.0 and supervisor. The server is connected to the internet and without using Talisman it has run smoothly so far.

List of things that I tried without any effect

  • temporarily stopped firewall
  • restarted nginx
  • both tried to access the website through its domain and IP address - the redirection to localhost:8000 remains
  • tried to run the app on other ports, e.g. 8000 for testing
  • stripped down the code to a mere mini tutorial that runs well on my development server but not on my production server. So I figured it can't be the app itself.
  • checked error logs and there is literally nothing, not in the nginx error log or python app error log. Access log shows nothing usual, the same as if everything checks out.
  • searched the Internet and found nothing that would point in the right direction and explain the failed redirect to localhost:8000

Here is a stripped down tutorial code that should run but doesn't run on my server:

from flask import Flask
from flask_talisman import Talisman

app = Flask(__name__)
Talisman(app)
app.secret_key = 'kungfoo'

@app.route('/', methods=['GET', 'POST'])
def index():
    return "Hello stackoverflow!"

if __name__ == "__main__":
    app.run(debug=True)

Solution

  • Well,

    proxy_set_header X-Forwarded-Proto $scheme; 
    

    does the trick in the nginx.conf within the server's location / {} block. This is stated in the gunicorn docs and can be easily missed...

    It is recommended to pass protocol information to Gunicorn. Many web frameworks use this information to generate URLs. Without this information, the application may mistakenly generate ‘http’ URLs in ‘https’ responses, leading to mixed content warnings or broken applications.