Home > Software engineering >  Is it possible to use nginx and redirect to correct path based on sub domains?
Is it possible to use nginx and redirect to correct path based on sub domains?

Time:01-01

I spot an issue when trying to configure the server. On the server side I am using Nginx.

The issue is that I got 1 domain and 2 subdomains like:

  1. www.test.com
  2. www.api.test.com
  3. www.panel.test.com

And these 3 urls are redirected to server with IP by Record A.

All i want to do is recognize from what url the user comes and return:

  1. if user comes from www.test.com - show static html
  2. if user comes from api - redirect to nodejs server which will serve data
  3. if user comes from panel - redirect to nodejs server which will serve html

I don't know how to recognize from what url the user comes. Is it possible to do that? If it is - just if you got some tutorials - i would be grateful! Unfortunately, I checked lots of tutorials, but I wasn't able to manage it.

Just as a information, I'm really bad at that piece (servers and configuration) - but want to learn it :)

Thank you!

CodePudding user response:

The server_name directive assigns rules to server blocks for specific domain/host names:

server {
  server_name test.com www.test.com;

  listen      80;  # IPv4
  listen [::]:80;  # IPv6
  
  root /var/www/static-files;
}

server {
  server_name api.test.com;
  ...
}

server {
  server_name panel.test.com;
  ...
}

Alternatively, the $host variable could be used within server blocks that serve multiple hosts:

server {
  server_name test.com www.test.com
              api.test.com
              panel.test.com;

  return 200 "This hostname is $host";
  ...
}
  • Related