Nginx & Django & Gunicorn - Redirecting subdomain to app
Solution 1:
You could have one gunicorn service per app:
/etc/systemd/system/blog.example.com.service
[Unit]
Description=gunicorn daemon for blog.example.com
Requires=gunicorn.socket
After=network.target
[Service]
User=example
Group=www-data
WorkingDirectory=/home/example/project/blog
ExecStart=/home/sammy/project/projectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/blog.example.com.sock \
project.wsgi:application
[Install]
WantedBy=multi-user.target
/etc/systemd/system/admin.example.com.service
[Unit]
Description=gunicorn daemon for admin.example.com
Requires=gunicorn.socket
After=network.target
[Service]
User=example
Group=www-data
WorkingDirectory=/home/example/project/admin
ExecStart=/home/sammy/project/projectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/admin.example.com.sock \
project.wsgi:application
[Install]
WantedBy=multi-user.target
Then point nginx to the respective .sock
files:
/etc/nginx/sites-available/blog.example.com
server {
listen 80;
server_name blog.example.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/example/project;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/blog.example.com.sock;
}
}
/etc/nginx/sites-available/admin.example.com
server {
listen 80;
server_name admin.example.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/example/project;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/admin.example.com.sock;
}
}
Solution 2:
You should use separate service and socket files for every app and use explicit hosts instead of unix sockets.
Change the terms like unix:/run/blog
with something like 127.0.0.1:8000
in your socket and service files. WorkingDirectory
parameter should be same in all service files, it should point the directory contains manage.py
. Finally you should set proxy_pass http://127.0.0.1:8000/blog/;
in your nginx config.
/etc/systemd/system/blog.example.com.socket
Unit]
Description=Gunicorn socket for blog.example.comg
[Socket]
ListenStream=8000
[Install]
WantedBy=sockets.target
/etc/systemd/system/blog.example.com.service
[Unit]
Description=gunicorn daemon for blog.example.com
Requires=blog.example.com.socket
After=network.target
[Service]
User=example
Group=www-data
WorkingDirectory=/home/example/project/blog
ExecStart=/home/sammy/project/projectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind 127.0.0.1:8000 \
project.wsgi:application
[Install]
WantedBy=multi-user.target
/etc/nginx/sites-available/blog-example:
server {
listen 80;
server_name blog.example.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/example/project;
}
location / {
include proxy_params;
proxy_pass http://127.0.0.1:9000/blog/;
}
}