乐闻世界logo
搜索文章和话题

Howt to set different Domains on Same IP in Nginx

1个答案

1

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:

  1. Listening Port: listen 80; indicates that both server blocks are listening on port 80, the standard port for HTTP.
  2. Server Name: The server_name directive specifies the respective domain. This is critical for Nginx to determine which server block handles different requests.
  3. Root Directory and Default Files: The root directive defines the root directory path for each domain, while the index directive 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 回复

你的答案