How to use django-hosts with Nginx

1.3k Views Asked by At

I have created one Django app which has two apps named "api" and "consumer". Now I want to use subdomains for both of this app. Like api.server.com and server.com. I searched online and found django-hosts so I implemented in my localhost and its working fine.

After that I deployed it on AWS EC2 instance and created subdomain in Godaddy and point both root domain and subdomain to my instance IP. Root domain is working fine but when I try to go api.server.com, it shows me default Welcome to Nginx screen. Please help me with this issue.

nginx.conf

server{
    server_name server.com, api.server.com;
    access_log  /var/log/nginx/example.log;

    location /static/ {
        alias /home/path/to/static/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/username/project/project.sock;
    }
}
2

There are 2 best solutions below

1
On

You don't need the , a simple space will do.

server_name server.com  api.server.com;

Also you can use wildcards, see the documentation.

server_name *.server.com;
1
On

You don't have to use a plugin (like django-hosts) to achieve what you are trying to do. Create 2 different nginx configurations for each subdomain you want to create (server.com and api.server.com), and forward requests from api.server.com to /api URL and request from server.com to /. Following is a basic example.

server.com

server {
    listen 80;

    server_name server.com;
        location / {
            proxy_pass http://127.0.0.1:3000$request_uri;
    }

}

api.server.com

server {
    listen 80;

    server_name api.server.com;
        location / {
            proxy_pass http://127.0.0.1:3000/api$request_uri;
    }

}

I recommend not to depend on 3rd party plugins unnecessarily. Refer https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/ for more details.