Unable to hit subdomain on VM: Ubuntu Server

Daniel asked:

I was sent here from stack overflow – sorry if this is the wrong forum. I’m trying to set up a local dev environment which simulates multiple servers. I’m just trying to learn more about this and this is the first time I’m doing this. In short, I cannot hit the subdomain on my nginx instance.

So Basically I have 3 Ubuntu VM’s running. One has Nginx, one has two node instances (web and api), and one is mongodb. If I were to get on the nginx server and curl localhost I get the web response (this is good). If I were to curl api.localhost I get the api response (this is also good). I think this means that nginx is properly configured.

The problem lies with the Node instances. On the Node Ubuntu server, I changed the hosts file to point the Nginx’s IP (192.168.134.147) to test.com and api.test.com. So now when I curl test.com on the node ubuntu server I get the web response (this is good). However, when I curl api.test.com I get the web response again. I want to be getting the api response. I’m not sure where I went wrong here. It doesn’t make sense to me that the nginx server can handle when it hits itself using api.localhost, but cannot handle when another server hits it.

If you need me to explain anything further, just let me know.

Also, when I said I pointed the ip to test.com and api.test.com, I just added this to my hosts file:
192.168.134.147 test.com api.test.com

Thanks!


edits:

Nginx Server Config

This is just off the top of my head, but it’s probably accurate. I didn’t change anything else, I just enabled these sites and disabled the default site.

Web server:

server {
    listen  80;
    server_name localhost;

    location / {
        # First attempt to serve request as file, then
        proxy_pass 192.168.134.145:3000;
        # as directory, then fall back to proxy
        try_files $uri $uri/ @proxy;
    }

    location @proxy {
         proxy_pass    192.168.134.145:3000;;
    }
}

Api Server:

server {
    listen  80;
    server_name api.localhost;

    location / {
        # First attempt to serve request as file, then
        proxy_pass 192.168.134.145:8080;
        # as directory, then fall back to proxy
        try_files $uri $uri/;
    }
}

Hosts File

The hosts file for the nginx server just has an addition:
127.0.0.1 localhost api.localhost

My answer:


You haven’t got server blocks for test.com and api.test.com. If you intend to serve these hostnames, they must appear in the server_name directive of a server block. Otherwise nginx will serve them from the default virtual host, which is either the one specified by default_server or the first virtual host.

See How nginx processes a request in the nginx documentation for the long explanation.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.