Question

How to get 2 different domains point to their own port without typing the port in the url with nginx?

So, I wanted to have 2 different subdomains work on the same droplet. Added them through digitalocean console. Then created folders for both of them using node.js and express and set up ports for each of them by modifying /home/subdomain/bin/www file as follows:

var port = normalizePort(process.env.PORT || '3002');

I followed this guideand setup nginx for both domains. Then I used pm2 start www for both sites.

Both domains are working, only problem is that I have to type the port number in the url (ex: subdomain.domain.net:3001), otherwise both domains redirect to the 2nd domain.

My 1st website’s nginx config file.

server {
  server_name subdomain.domain.net;
  listen 80;
  location / {
	  

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://my droplet's IP:3001;
    proxy_redirect off;
  }
}

My 2nd website’s nginx config file.

server {
  server_name subdomain.domain.net;
  listen 80;
  location / {
	  

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://my droplet's IP:3002;
    proxy_redirect off;
  }
}

How can I get both domains working so that I don’t have to type the port number in the url?


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hello friend!

You are definitely thinking on the right path here to make this function correctly. My instinct is telling me that there is either an error with the Nginx config, or one isn’t being loaded for some reason. You can’t really trace an error here because as far as the web server knows it’s functioning as configured.

So I suppose my questions are:

  1. Did you restart the web server after configuring? (It sounds obvious but you never know what you don’t ask)
  2. Is the config file (or the config files) containing both subdomains loaded by the primary config file? For example, if it’s all in nginx.conf it should be loaded, if nginx.conf is including additional files, is the instructed include covering both server blocks?

Kind Regards, Jarland