NGINX server_name: How to use it, Where you need it
The server_name config directive tells NGINX how to route client requests. We can use server_name to match multiple domains, split out IP-based requests and work on localhost.
What server_name does
server_name helps NGINX route requests between multiple server blocks. Server blocks allow you to define backend services and specific ways to handle those requests. The server_name tells NGINX which server block to use.
This directive is really useful for SSL termination and domain based routing. For example, you may want to serve your static files from static.mydomain.com with specific compression settings. But, you may want different compression settings for api.mydomain.com. Server_name can help you with this.
server_name is not required
You can ignore the server_name directive if you wish. This is useful when you don’t need domain routing or you only have one backend service. If you omit the server_name directive, NGINX will simply use the first server block.
server_name _ (underscore)
You can also set server_name to “_”. This is basically the same as omitting the server_name directive. It will mark this server block as the catch-all block.
Using server_name for localhost
For local development or machine tests, you can define a localhost server_name. Any requests to localhost or 127.0.0.1 will be routed to this server block. Here’s an example of how to do this:
server_name: 127.0.0.1 localhost;
Using server_name for multiple domains
You can define multiple domains in your server_name directive. Simply list your domains with spaces or newlines between each domain. Don’t forget to end your directive with a semicolon. Here’s an example:
server_name: mydomain.com api.mydomain.com;
Using server_name wildcards
You can also use wildcards. This allows us to match multiple domains without having to explicitly list them. For example you could set your server_name to *.mydomain.com instead of app.mydomain.com api.mydomain.com static.mydomain.com.
Wildcards only work at the start or end of the domain name (e.g. *.domain.com or domain.*). You can’t put a wildcard in the middle of the domain name. For that you will need to use a regular expression.
Using server_name regular expressions
NGINX also supports PCRE compatible regex for the server_name. You can write your regular expressions just like you would a domain name. If you want to enter multiple regular expressions, just add them with a space separating each expression. Here’s a few examples:
Using server_name IP Addresses
You can enter IP addresses in the server_name block. IP addresses will match requests where the Host field is an IP address (e.g. http://10.0.0.23/myfile.html). For example: