This post will explain how to configure Nginx to work with Amazon’s Elastic Load Balancer healthcheck, and also listen to multiple domains at the same time. With this setup you’ll be able to clone servers that listen to multiple domains and scale your infrastructure effortlessly.

First we’ll add our domains like we normally would, the first of which is just a simple static server.

server {
    listen 80;
    root /home/kevin/ksloan.net;
    server_name ksloan.net;
}

For our second domain we’ll configure a proxy to our node.js/api server.

server {
    listen 80;
    server_name api.ksloan.net
    location / {
        proxy_pass http://127.0.0.1:8080;
        access_log off;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_hide_header X-Frame-Options;
    }
}

Finally, we’ll configure our default ELB healthcheck response server. When the Amazon ELB checks your server health status, nginx will respond using the what it considers the default server. Nginx picks first server it comes across as default server unless otherwise explicitly stated. If your server blocks are in different files, that means it will be decided alphabetically. In order to be safe, we should explicitly make this server our default like so:

server {
    listen 80 default_server;
    server_name "";
    location /health {
        return  200;
    }
}

We respond with a 200 so AWS knows your server is still alive and kicking. Note that this only checks that nginx is up and running properly. If you want AWS to monitor your node server you can also forward the healthcheck to your node server and respond from there. That way, if your node.js server crashes then that EC2 instance will be removed from the ELB until it has a chance to reboot.

Also, make sure your ELB healthcheck location and port are configured match what is set in the EC2 Management Console here:

EC2 Console
EC2 Console

If you set it up correctly, you will be able to clone this server/nginx config and scale your infrastructure for your billions of users!