How to easily set up Subdomain routing in Nginx

<3 Nginx

As i was going through the fun process of setting up a Digital Ocean instance for my blog, I realized that i had a couple other projects I would like to spin of in the same instance.

All of those projects are web applications, and thus, require an opened port to receive the incoming requests.

Previously I had been happy with Dokku, an open source Docker-based heroku,  but the lack of support (it is an open source project after all) and my lack of Docker knowledge made me spend more time fixing dokku than I was happy with.

Eventually, I decided to just use git to control my production apps and implement the subdomain routing in Nginx (pronounced engine-x), which seems easy except for the fact that I could not find any easy example of subdomain routing online.

Nginx Implementation.

First of all, install Nginx.

sudo apt-get install nginx for Linux systems or,

brew install nginx for Mac.

Then edit the default Nginx configuration file:

sudo nano /etc/nginx/sites-enabled/default

In my case, I wanted to set up the following routes:

And I used this snippet for the nginx configuration file:

server {
    listen 80;
server_name manugarri.com;
        location / {
            proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $remote_addr;
             proxy_set_header Host $host;
            proxy_pass http://127.0.0.1:{PORT1};
        }
}

server {
    listen 80;
server_name colores.manugarri.com;
        location / {
            proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $remote_addr;
             proxy_set_header Host $host;
            proxy_pass http://127.0.0.1:{PORT2};
        }
}

server {
    listen 80;
server_name blog.manugarri.com;
        location / {
            proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $remote_addr;
             proxy_set_header Host $host;
            proxy_pass http://127.0.0.1:{PORT3};
        }
}

(note that the {PORT NUMBERS} should be replaced by the ports your applications are listening to.

As you see, the file it's easy to understand. Nginx listens to all the specific subdomains (or the main domain) and redirect to the proper app.

Let me know your questions!.