You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Nginx同一IP的不同端点部署不同应用?server_name配置咨询

当然可行!不过得先澄清一下:你要做的不是「基于IP的虚拟主机」,而是基于URI路径的路由配置——因为两个应用都共享同一个IP地址,只是通过不同的路径(/foo和/bar)来区分。

关于server_name指令,因为你是针对单个IP配置,直接把它设为你的目标IP210.32.45.189就可以了;如果这个IP上只有这一个Nginx服务,也可以用_来匹配所有未被其他server块匹配的请求,不过写具体IP会更精准。

下面给你两种常见场景的配置示例:

场景1:应用是静态文件(HTML/CSS/JS等)

如果你的两个应用都是静态资源,sites-available里的配置可以这么写:

server {
    listen 80;
    server_name 210.32.45.189;

    # 处理/foo路径的请求
    location /foo {
        # 指向foo应用的静态文件根目录
        root /var/www/foo-app/;
        index index.html index.htm;
        # 可选:如果希望路径里的/foo被透明处理(比如访问/foo/about时实际读取foo-app/about)
        try_files $uri $uri/ /foo/index.html;
    }

    # 处理/bar路径的请求
    location /bar {
        root /var/www/bar-app/;
        index index.html index.htm;
    }
}

场景2:应用是动态服务(反向代理到后端)

如果你的应用是运行在本地端口的动态服务(比如Node.js、Django、Spring Boot等),就用proxy_pass来转发请求:

server {
    listen 80;
    server_name 210.32.45.189;

    location /foo {
        # 假设foo应用运行在localhost:3000,末尾的/要加上,避免路径拼接错误
        proxy_pass http://localhost: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;
    }

    location /bar {
        # 假设bar应用运行在localhost:8080
        proxy_pass http://localhost:8080/;
        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;
    }
}

配置后的操作步骤

  1. 把sites-available里的配置文件软链接到sites-enabled目录:
    sudo ln -s /etc/nginx/sites-available/your-config.conf /etc/nginx/sites-enabled/
    
  2. 测试配置是否合法:
    sudo nginx -t
    
  3. 如果测试通过,重启Nginx生效:
    sudo systemctl restart nginx
    

如果需要HTTPS支持,只需要把listen 80改成listen 443 ssl,并添加SSL证书相关配置即可。

内容的提问来源于stack exchange,提问作者CaptainDriftwood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:10:19