Serving multiple domains with same port in nginx
Posted by Suyash Singh
on October 7, 2022In this instance of Keep It Crisp, let’s quickly see how you can leverage a single instance of nginx to listen and serve multiple concurrent requests for different subdomains.
Nginx is a multipurpose software — it can load balance, proxy services, manage multiple domains, cache requests, solve authentication tasks, act as an API gateway and more…
In nginx’s unit of configuration, in each server configuration block you can listen to requests made from different hosts for specific ports like this:
server {
#listen to requests made to port 81
listen 81;
#requests made from multiple hosts
server_name suyashsingh.in www.suyashsingh.in <SOME_OTHER_HOST_1>;
location / {
#redirect to HTTPS endpoint
return 301 https://suyashsingh.in;
}
}
What’s even more simpler in nginx is that you can have multiple such server blocks as part of the nginx configurations:
# server block for dawki subdomain
server {
#listen to requests made to port 81
listen 81;
#requests made from these domains
server_name dawki.suyashsingh.in;
location / {
#redirect to HTTPS endpoint
return 301 https://dawki.suyashsingh.in;
}
}
# server block for jambox subdomain
server {
#listen to requests made to port 81
listen 81;
#requests made from these domains
server_name jambox.suyashsingh.in;
location / {
#redirect to HTTPS endpoint
return 301 https://jambox.suyashsingh.in;
}
}
Bonus tip
It is a common practice in nginx to use regex captures to eliminate similar blocks like this:
location ~ ^/(path1|path2/)(.+)$ {
proxy_pass http://<IP>/$1$2;
... rest of configuration directives ...
}