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

Nginx配置location块后子页面无法加载,求问题排查及解决办法

Nginx子页面404问题排查与解决

问题根源分析

初始默认配置的问题

你最初的location /配置:

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

当访问/about时,Nginx会按顺序尝试:

  1. 查找文件/var/www/test.domain.com/about(无后缀)
  2. 查找目录/var/www/test.domain.com/about/
  3. 都找不到则返回404

但你的目标文件是about.html,不在上述查找路径里,所以自然返回404。

新增location块的问题

你添加的location /about和location /contact配置存在路径拼接错误:

location /about {
  root /var/www/test.domain.com;
  index about.html;
}

Nginx会将root路径与location路径拼接,去寻找/var/www/test.domain.com/about/about.html,但你的about.html实际在根目录/var/www/test.domain.com/下,这个拼接后的路径不存在,所以依然返回404。

正确解决方案

方案一:修改默认location(推荐,无需单独配置子页面)

直接调整try_files规则,让Nginx尝试匹配带.html后缀的文件:

server {
  root /var/www/test.domain.com;
  server_name test.domain.com;
  listen 443 ssl;

  ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;

  if ($scheme != "https") {
    return 301 https://$host$request_uri;
  } # managed by Certbot

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

此时访问/about,Nginx会依次尝试:

  1. /var/www/test.domain.com/about
  2. /var/www/test.domain.com/about.html(匹配到你的目标文件)
  3. /var/www/test.domain.com/about/
  4. 都找不到返回404

方案二:单独配置精确匹配的location块(不推荐,冗余)

如果一定要为子页面单独配置,可以用精确匹配的location,直接重写到对应的HTML文件:

server {
  root /var/www/test.domain.com;
  server_name test.domain.com;
  listen 443 ssl;

  ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;

  if ($scheme != "https") {
    return 301 https://$host$request_uri;
  } # managed by Certbot

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

  location = /about {
    rewrite ^ /about.html last;
  }

  location = /contact {
    rewrite ^ /contact.html last;
  }
}

验证与生效

修改配置后,先测试Nginx配置是否合法:

nginx -t

如果提示test is successful,再重载Nginx使配置生效:

systemctl reload nginx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:22:29