SoFunction
Updated on 2025-04-11

Super detailed usage guide for server_name in Nginx

Introduction

server_nameIt is an important directive in the Nginx configuration file to specify which domain names the Nginx server block (or virtual host) should respond to. By correct configurationserver_name, you can host multiple different websites on the same server and make sure that requests for each domain name are processed correctly.

DNS resolution process

  • Client initiates a request: When the user enters a domain name in the browser (such as) When the browser sends a query request to the local DNS server.

  • Recursive query: The local DNS server will check its cache. If the IP address corresponding to the domain name is found, it will be returned directly to the client; if it is not found, it will continue to recursively query other DNS servers (such as root DNS server, top-level domain DNS server, etc.) until the target IP address is found.

  • Return result: Once the target IP address is found, the DNS server will return the result to the client, and the browser can use the IP address to establish a connection with the target server.

  • Cache results: To improve efficiency, DNS servers usually cache query results for a period of time (called TTL, Time To Live) so that subsequent same queries can directly get results from the cache without the need for a complete parsing process again.

The role of host files

In development environments, we usually useHost File/etc/hostsorC:\Windows\System32\drivers\etc\hosts) to simulate DNS resolution. The host file allows us to map specific domain names locally to a specified IP address without relying on an external DNS server. This is very useful for testing and development because it allows for quick configuration of custom domain names and does not affect other users' network environment.

For example, add the following line to the host file:

192.168.154.101 admin.dhl101

This line of configuration indicates that when the browser tries to accessadmin.dhl101When  , it will directly resolve to the IP address192.168.154.101, without querying external DNS servers.

DNS and Nginx relationship

Nginx Useserver_nameDirective to match the HTTP requestHostheader field to determine which oneserverThe block should process the request. Therefore, the result of DNS resolution (i.e., the IP address corresponding to the domain name) determines which server the request will be sent to, while Nginx will be based onserver_nameThe instructions further determine the specific processing logic.

For example, suppose you have two servers, hosted separatelyand. User enters in the browser, DNS will resolve it to the IP address of a server, and then Nginx will followserver_nameThe instruction determines whether the server should handle the request.

The role of server_name

server_nameThe directive tells Nginx that when receiving an HTTP request, if the   in the request header isHostThe field matches the specified domain name, and the request should be made by this specificserverBlocks are used to process. This makes it possible to host websites with multiple different domain names on the same server.

Basic usage

The easiestserver_nameThe configuration is to specify a specific domain name.serverpiece. For example:

server {
    listen 80;
    server_name ;

    root /var/www/;
    index ;

    location / {
        try_files $uri $uri/ =404;
    }
}

In this example, Nginx will check all incoming HTTP requests and view the request headerHostField. ifHostThe value of the field is, then Nginx will use thisserverConfiguration in the block to handle the request.

Wildcards and regular expressions

server_nameSupports wildcards and regular expressions to match domain names more flexiblely.

Wildcard

  • Prefix wildcard*.Can match any.The ending subdomain name, such aswait.

    server {
        listen 80;
        server_name *.;
    
        root /var/www/;
        index ;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    
  • Suffix wildcard:Nginx does not directly support suffix wildcards, but similar functions can be implemented through regular expressions.

Regular expressions

use~The beginningserver_namecan contain regular expressions. For example:

server {
    listen 80;
    server_name ~^(?<sub>.+)\.example\.com$;

    root /var/www/$;
    index ;

    location / {
        try_files $uri $uri/ =404;
    }
}

In this example,(?<sub>.+)is a capture group that allows you to reference the matching subdomain part in subsequent configurations.

Default server

If you want oneserverBlocks are the default server (i.e., when no other server blocks match), you can use the following method:

  • Empty stringserver_name "";Indicate thisserverBlock is the default server.
  • Underlineserver_name _;It can also represent the default server.

For example:

server {
    listen 80 default_server;
    server_name _;

    root /var/www/default;
    index ;

    location / {
        try_files $uri $uri/ =404;
    }
}

Multi-domain configuration

You can be for the sameserverBlocks specify multiple domain names, separated by spaces. For example:

server {
    listen 80;
    server_name  ;

    root /var/www/;
    index ;

    location / {
        try_files $uri $uri/ =404;
    }
}

In this way, Nginx willandAll requests are routed to thisserverpiece.

Subdomain configuration

If you want toSubdomain name (such asand) Create independentserverBlocks can be configured according to the following steps.

Modify the host file

First, you need to add an entry to the new subdomain in the host file. Assume that you have already set it in the host file192.168.154.101 , now you need to addand

Windows

  • Open Notepad (run as administrator), and then openC:\Windows\System32\drivers\etc\hostsdocument.
  • Add the following line at the end of the file:
    192.168.154.101 
    192.168.154.101 
    

macOS and Linux

  • Open the terminal and edit it using a text editor (such as nano, vim, emacs, etc.)/etc/hostsdocument. For example, using the nano editor, you can run:

    sudo nano /etc/hosts
    
  • Add the following line at the end of the file:

    192.168.154.101 
    192.168.154.101 
    
  • Save and exit the editor (for nano, pressCtrl + X, and then pressYConfirm to save the changes, and finally pressEnterquit).

Configure Nginx

Next, we need to use Nginx forandCreated separatelyserverpiece.

#Main Site Configurationserver {
    listen 80;
    server_name  ;

    root /var/www/;
    index ;

    location / {
        try_files $uri $uri/ =404;
    }
}

# API subdomain configurationserver {
    listen 80;
    server_name ;

    root /var/www/;
    index ;

    location / {
        try_files $uri $uri/ =404;
    }

    # If you have an API service, you can add the following configuration    location /api {
        proxy_pass http://localhost:3000;  # Assume that the API service runs on the local port 3000        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# Admin subdomain configurationserver {
    listen 80;
    server_name ;

    root /var/www/;
    index ;

    location / {
        try_files $uri $uri/ =404;
    }
}

Combined with port monitoring and server_name

If you want Nginx to listen for requests on non-standard ports (such as 8082) and only handle requests for specific domain names, you canlistenThe IP address and port combination are clearly specified in the instruction.

For example, suppose you want Nginx to be in192.168.154.101Listen to port 8082 and only handleadmin.dhl101Request:

server {
    listen 192.168.154.101:8082;
    server_name admin.dhl101;

    root /var/www/login;
    index ;

    location / {
        try_files $uri $uri/ =404;
    }
}

Host file configuration

Make sure that your host file has the following entries so that the browser can parse correctly.admin.dhl101

192.168.154.101 admin.dhl101

Testing and Verification

  • Test configuration file

    • After modifying the Nginx configuration file, first test the configuration file for syntax errors:
      sudo nginx -t
      
  • Overload Nginx

    • If there is no problem, reload Nginx to make the configuration take effect:
      sudo systemctl reload nginx
      
      Or, if your system is using a different initialization system, you may need to use itsudo service nginx reload
  • Access URL

    • Open the browser and visithttp://admin.dhl101:8082/, confirm whether it can load normally/var/www/loginContents under the directory.

Other precautions

  • Firewall settings: Make sure your firewall allows traffic through port 8082. You can check and configure firewall rules using the following command:

    sudo ufw allow 8082/tcp  # For UFWsudo firewall-cmd --add-port=8082/tcp --permanent  # for firewalldsudo firewall-cmd --reload
    
  • SELinux Settings(Applicable to CentOS/RHEL): If your system has SELinux enabled, make sure Nginx has permission to listen to non-standard ports. You can use the following command:

    sudo semanage port -a -t http_port_t -p tcp 8082
    
  • HTTPS Configuration: If you wish foradmin.dhl101Configure HTTPS, you can usemkcertThe tool generates a self-signed certificate. Here is an example of HTTPS configuration:

    server {
        listen 192.168.154.101:8082 ssl;
        server_name admin.dhl101;
    
        ssl_certificate /path/to/admin.;
        ssl_certificate_key /path/to/admin.;
    
        root /var/www/login;
        index ;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    

Summarize

By correct configurationserver_name, you can host multiple different websites on the same server and make sure that requests for each domain name are processed correctly.server_nameSupports a variety of matching methods, including specific domain names, wildcards and regular expressions, which can be flexibly used according to actual needs. In addition, combining port listening and host file configuration, you can easily implement complex domain name and port mapping to meet the needs of various development and production environments.

If you have more questions or need further assistance, feel free to consult the official Nginx documentation or seek community support.

References

  • Nginx official documentation
  • Nginx server_name command
  • mkcert: Generate a self-signed certificate

I hope this note can help you better understand and use the Nginxserver_nameInstructions.

This is all about this article about server_name in Nginx. For more related content on server_name in Nginx, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!