You need to enable JavaScript to run this app. 配置Nginx vhosts按路径首段映射项目,访问时跳转默认页
优惠活动
大模型
产品
解决方案
定价
更多

配置Nginx vhosts按路径首段映射项目,访问时跳转默认页

问题根因

跳Nginx默认页的现象是配置层面的3处硬错误叠加导致,没有环境或网络类的玄学问题:

  • 443服务块的server_name配置完全无效:该参数仅支持填写需要匹配的域名/通配符/正则,不能拼接路径段、未定义的Nginx变量(原配置写的example.com/$1 www.example.com/$1带斜杠和无来源的$1变量,属于非法值),Nginx无法将这个块绑定到example.com域名上,所有对该域名的HTTPS请求自然落到内置的默认欢迎页server块上
  • root路径拼接逻辑错误:Nginx处理root的固定规则是「root指定的目录 + 请求的完整URI路径」。你在location /projectname块里写root /usr/share/nginx/html/projectname,实际请求/projectname/index.html时,Nginx会拼接路径去/usr/share/nginx/html/projectname/projectname/index.html找文件,这个路径根本不存在,就算块匹配上了也读不到项目内容
  • try_files回退路径错位:配置里写的回退地址/index.html是站点根路径下的文件,不是项目目录下的入口文件,找不到对应文件时就会触发默认页返回
  • 细节疏漏:原配置的root路径末尾多打了一个空格,也会导致路径匹配失败
排查步骤
  • 执行配置校验命令nginx -t,确认没有阻断Nginx启动的语法报错
  • 查看配置里定义的access、error日志文件,看访问https://example.com/projectname时,实际命中的server块、返回状态码、Nginx尝试查找的文件路径
  • 找到Nginx内置的默认server块位置(一般在Debian系的/etc/nginx/sites-enabled/default,或CentOS系的主配置文件内),确认其listen配置带default_server标记——所有匹配不到正式server块的请求,都会被默认块接走返回欢迎页
修正后的可用配置
# 80端口强制跳转HTTPS的块(原有逻辑无问题,保留即可)
server {
    listen 80;
    server_name example.com www.example.com;
    rewrite ^/(.*) https://example.com/$1 permanent;
}

# 443正式服务块
server {
    listen       443 ssl;
    listen       [::]:443 ssl;

    ssl_certificate "/etc/ssl/XX.pem";
    ssl_certificate_key "/etc/ssl/XX.key";
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
    # 修正server_name:仅填写纯域名,不拼接路径、不写无定义的变量
    server_name  example.com www.example.com;

    access_log /var/log/nginx/nginx.vhost.access.log;
    error_log /var/log/nginx/nginx.vhost.error.log;

    # 方案1:使用root配置(推荐,逻辑更简单)
    # 将root指到项目的上级目录,Nginx会自动拼接/projectname路径定位到目标项目目录
    root /usr/share/nginx/html;
    location /projectname {
        index  index.html;
        # 修正回退路径,指向项目目录下的index.html
        try_files $uri $uri/ /projectname/index.html?$args;
    }

    # ---
    # 方案2:如果需要将项目路径直接绑定到location,使用alias替代root
    # location /projectname/ {
    #     alias /usr/share/nginx/html/projectname/;
    #     index index.html;
    #     try_files $uri $uri/ /projectname/index.html?$args;
    # }
}
生效验证
  • 改完配置后执行nginx -s reload重载配置
  • 访问https://example.com/projectname,确认返回的是/usr/share/nginx/html/projectname下的index.html内容
  • 未匹配到项目路径的请求不会误触项目页面逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 20:24:10