Tuesday, September 3, 2013

Django & Nginx - 2 projects, 2 domains, 1 machine

Assuming I have 2 Django projects which are running on port 8000 (project1) and port 8080 (project2) in a same machine. I want to make those 2 projects publicly accessible via 2 different domains:

my.firstdomain.com --> project1
my.seconddomain.com --> project2

and not via 2 different ports:

my.domain.com --> project1
my.domain.com:8080 --> project2


The solution is to create another server block in the nginx for the second project:

1. Edit the nginx config file /etc/nginx/site-available/default:

upstream project1 {
    server localhost:8000 fail_timeout=0;
}

upstream project2 {
    server localhost:8080 fail_timeout=0;
}

server {
    listen 80;
    server_name my.firstdomain.com;
    access_log /home/projects/logs/access_prj1.log;
    error_log /home/projects/logs/error_prj1.log;

    location /site_media/ {
        alias /home/projects/project1/site_media/;
    }

    location / {
        proxy_pass http://project1;
    }

}

server {
    listen 80;
    server_name my.seconddomain.com;
    access_log /home/projects/logs/access_prj2.log;
    error_log /home/projects/logs/error_prj2.log;

    location /site_media/ {
        alias /home/projects/project2/site_media/;
    }

    location / {
        proxy_pass http://project2;
    }

}



2. Restart the nginx:

$ sudo service nginx restart