When configuring Nginx, if you want a single server (same IP address) to support multiple domains, you can achieve this by setting up multiple server blocks. Each server block is configured for a single domain, allowing Nginx to distinguish and route requests to the correct website based on the Host header.
Example:
Assume we have two domains: example.com and test.com, which are served by Nginx on the same IP address. Here is a basic configuration example:
nginx# For example.com server { listen 80; # Listening on port 80 server_name example.com; # Set server name to example.com location / { root /var/www/example; # Website root directory index index.html index.htm; # Default files } } # For test.com server { listen 80; # Listening on port 80 server_name test.com; # Set server name to test.com location / { root /var/www/test; # Website root directory index index.html index.htm; # Default files } }
Explanation:
- Listening Port:
listen 80;indicates that both server blocks are listening on port 80, the standard port for HTTP. - Server Name: The
server_namedirective specifies the respective domain. This is critical for Nginx to determine which server block handles different requests. - Root Directory and Default Files: The
rootdirective defines the root directory path for each domain, while theindexdirective specifies the default file to return when a request targets a directory.
Summary:
With this configuration, Nginx can listen for requests from different domains on the same IP address and route them to the correct paths based on server_name. This setup is highly flexible and easy to extend, enabling you to add more domains and corresponding server blocks with minimal effort.
2024年8月16日 00:20 回复