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

在Ubuntu 22.04服务器用NGINX部署多个ASP.NET Core服务遇阻

问题诊断与解决方案

核心问题

你的Nginx配置存在逻辑错误:API对应的server { ... }块中,server_name compliance是域名匹配规则,而非路径前缀。当你用curl http://{你的IP地址}/compliance/访问时,Nginx会尝试在当前匹配到的server块(比如静态页面的那个)里寻找/compliance/路径,自然返回404,根本不会转发到localhost:5001的API服务。


解决方案一:通过路径前缀转发API(无需域名)

如果希望通过http://{你的IP地址}/compliance/访问API,可按以下方式修改Nginx配置:

方式1:在静态页面server块中新增API转发规则

server {
    listen 80;
    listen [::]:80;
    root /var/www/html/web2.webdock.io;
    index index.html index.htm;
    server_name web2.webdock.io;

    # 静态页面访问规则
    location / {
        try_files $uri $uri/ =404;
    }

    # API转发规则(注意proxy_pass末尾的斜杠,避免路径拼接错误)
    location /compliance/ {
        proxy_pass         http://localhost:5001/;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

方式2:单独创建监听IP的server块

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # 静态页面根路径(支持通过IP直接访问静态页)
    root /var/www/html/web2.webdock.io;
    index index.html index.htm;

    # API转发规则
    location /compliance/ {
        proxy_pass         http://localhost:5001/;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }

    # 静态页面访问规则
    location / {
        try_files $uri $uri/ =404;
    }
}

解决方案二:通过域名访问API(推荐生产环境)

如果希望用http://compliance/(或自定义正式域名)访问API:

  1. 将compliance域名解析到你的服务器IP
  2. 修改API的Nginx配置,确保server_name与域名完全匹配:
server {
    listen 80;
    listen [::]:80;
    server_name compliance;

    location / {
        proxy_pass         http://localhost:5001;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}
  1. 访问时使用curl http://compliance/(需确保本地DNS能解析该域名,或在hosts文件中临时绑定IP与域名)

验证步骤

  1. 检查Nginx配置语法合法性:sudo nginx -t
  2. 重启Nginx使配置生效:sudo systemctl restart nginx
  3. 测试API访问:
    • 方案一:curl http://{你的IP地址}/compliance/
    • 方案二:curl http://compliance/
  4. 若仍有问题,查看Nginx错误日志排查:sudo tail -f /var/log/nginx/error.log

内容的提问来源于stack exchange,提问作者R.Haughton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:03:17