插件窝 干货文章 windows下Nginx多域名怎么配置

windows下Nginx多域名怎么配置

example 配置 Nginx server 254    来源:    2025-04-21

Windows下Nginx多域名配置指南

在Windows环境下配置Nginx支持多域名(虚拟主机)是一个常见的需求。以下是详细的配置步骤:

基本配置步骤

  1. 编辑nginx.conf文件

    • 通常位于 C:\nginx\conf\nginx.conf
    • http 块内添加 include 指令引入虚拟主机配置
    http {
       # 其他配置...
       include vhosts/*.conf;
    }
    
  2. 创建虚拟主机配置文件

    • conf 目录下创建 vhosts 文件夹
    • 为每个域名创建单独的配置文件,例如 example1.confexample2.conf

多域名配置示例

示例1:两个域名指向不同目录

example1.conf

server {
    listen 80;
    server_name example1.com www.example1.com;

    root C:/websites/example1;
    index index.html index.htm;

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

example2.conf

server {
    listen 80;
    server_name example2.com www.example2.com;

    root C:/websites/example2;
    index index.html index.htm;

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

示例2:HTTPS配置(需要SSL证书)

server {
    listen 443 ssl;
    server_name secure.example.com;

    ssl_certificate C:/ssl/secure.example.com.crt;
    ssl_certificate_key C:/ssl/secure.example.com.key;

    root C:/websites/secure;
    index index.html;

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

本地开发环境配置

如果用于本地开发,可以修改hosts文件(C:\Windows\System32\drivers\etc\hosts)添加:

127.0.0.1 example1.com
127.0.0.1 example2.com
127.0.0.1 secure.example.com

常用命令

  1. 测试配置是否正确

    nginx -t
    
  2. 重新加载配置(不中断服务)

    nginx -s reload
    
  3. 重启Nginx

    nginx -s stop
    nginx
    

注意事项

  1. 路径中使用正斜杠 / 而不是反斜杠 \
  2. 确保每个 server 块的 server_name 唯一
  3. 配置文件修改后需要重新加载或重启Nginx
  4. 如果使用非标准端口(非80/443),确保防火墙允许该端口
  5. 对于生产环境,建议配置HTTPS并启用HTTP到HTTPS的重定向

高级配置

重定向HTTP到HTTPS

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

负载均衡配置

upstream backend {
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
}

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://backend;
    }
}

通过以上配置,您可以在Windows环境下轻松实现Nginx的多域名支持。根据实际需求调整配置即可。