Django and Flask on same nginx server

Question:

I currently have a Djago app running on my main site when I visit mysite.com. However, I’d like mysite.com/flaskapp to run a separate Flask application. I’m able to set up two nginx site-enabled config files and run each app on a different port but, for various reasons, I’d like to run them all on the same port (if possible). When I configure my flaskapp/ location in my nginx server file I get a 404 error.

Here’s my supervisor config file:

[program:MYSITE]
command=/var/www/html/MYSITE/prodenv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/MYSITE.sock MYSITE.wsgi
directory=/var/www/html/MYSITE/public_html
autostart=true
autorestart=true
stderr_logfile=/var/log/MYSITE.err.log
stdout_logfile=/var/log/MYSITE.out.log


[program:FLASKAPP]
directory=/var/www/html/MYSITE/public_html/FLASKAPP/api
command=/var/www/html/MYSITE/public_html/FLASKAPP/venv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock FLASKAPP:app
autostart=true
autorestart=true
stderr_logfile=/var/log/FLASKAPP.err.log
stdout_logfile=/var/log/FLASKAPP.out.log

And my nginx site-enabled file:

server {
    listen 80;
    listen [::]:80;

    server_name MYSITE;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static/ {
        root /var/www/html/MYSITE/public_html;
        expires 30d;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/var/www/html/MYSITE/public_html/MYSITE.sock;
    }

    location /FLASKAPP/ {
        include proxy_params;
        proxy_pass http://unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock; 
    }
}

I wrote a function to check the request url

    @app.errorhandler(404)
    def page_not_found(error):
         return 'This route does not exist {}'.format(request.url), 404

Which returns:

This route does not exist http://MYSITE/FLASKAPP

The Flask app is clearly working, but the routing is screwed up. How can I fix this?

Asked By: pnus

||

Answers:

I figured it out. I rewrote the url to remove the subdirectory and now it all works:

      rewrite ^/FLASKAPP(.*)$ $1 break;
Answered By: pnus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.