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

Nginx迁移配置后报错"upstream" directive is not allowed here求助

错误原因

upstream 是Nginx HTTP模块的专属指令,只能在 http 配置块的上下文中使用。你当前的主配置文件 nginx.conf 中,events 块结束后直接编写了 upstream 和 server 块,没有将这部分内容包裹在 http 块内,因此触发了语法校验错误。

之前的服务器配置可以正常运行,是因为你之前是将这部分虚拟主机配置存放在 /etc/nginx/sites-available/ 这类子配置目录下,这些子配置是被主配置文件 http 块内的 include 指令引入的,本身就处于合法的 http 上下文内,因此不需要额外加 http 块。

修复方案

直接在 events 块结束后新增 http 块,将所有 upstream、server 配置都包裹在 http 块内即可,完整参考配置如下:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    # 基础必备配置,引入MIME类型定义
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 通用配置可按需调整
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    sendfile on;
    keepalive_timeout 65;

    upstream LoadBalancer {
        server 127.0.0.1:6666;
    }
    upstream ProxyStream {
        server 127.0.0.1:6868;
    }
        
    server {
        listen 80;
        server_name proxy.yourdomain.com;
        
        location / {
            proxy_pass http://LoadBalancer;
            proxy_http_version 1.1;
            proxy_send_timeout   600;
            proxy_read_timeout   600;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
        
    server {
        listen 80;
        server_name sv1.yourdomain.com;
        
        location / {
            proxy_pass http://ProxyStream;
            proxy_http_version 1.1;
            proxy_send_timeout   600;
            proxy_read_timeout   600;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }

    # 保留默认的子配置引入规则,兼容原有站点配置
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

修改完成后执行以下命令校验配置语法:
nginx -t
如果返回 test is successful 字样,再执行重载配置命令生效:
systemctl reload nginx

额外建议

按照Debian/Ubuntu系Nginx的默认配置规范,更推荐你将站点相关的 upstream、server 配置单独存放在 /etc/nginx/sites-available/ 目录下的独立文件中,再通过软链到 /etc/nginx/sites-enabled/ 目录加载,避免直接修改主配置文件导致结构混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:09:02