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

Nginx配置疑问:访问domain.com/x报404,如何实现无.html访问x.html?

Nginx访问无后缀URL返回404的问题解决

问题场景

当前Nginx配置:

server {
    listen 80;

    location /x {
        root /templates;
        index x.html;
    }
     location / {
        root /templates;
        index index.html;
    }
}

目录结构:

templates
| - index.html
| - x.html

访问domain.com能正常显示index.html,访问domain.com/x.html也正常,但访问domain.com/x返回404 Not Found。

问题原因

当请求domain.com/x时,Nginx匹配到location /x块,结合root /templates配置,它会尝试寻找**/templates/x目录下的x.html文件**,但实际目录里并没有x子目录,只有根目录下的x.html,因此找不到文件返回404。

解决方案

方案1:针对单个路径配置(仅适配/x)

修改location /x块,使用try_files指令让Nginx尝试匹配文件本身或带.html后缀的文件:

server {
    listen 80;

    location /x {
        root /templates;
        try_files $uri $uri.html =404;
    }
     location / {
        root /templates;
        index index.html;
    }
}

try_files $uri $uri.html =404的逻辑:先找$uri对应的文件(即/templates/x),找不到就找$uri.html(即/templates/x.html),都找不到则返回404。

方案2:通用配置(适配所有无后缀URL)

如果需要让所有类似domain.com/xxx的请求自动匹配xxx.html,可以简化配置,在根location中加入try_files:

server {
    listen 80;

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

无需单独配置location /x,所有无后缀请求都会自动尝试匹配对应.html文件,同时保留根路径默认访问index.html的逻辑。

方案3:精确匹配映射(针对单个路径)

如果只想对/x做精准映射,可使用alias直接指定文件:

server {
    listen 80;

    location = /x {
        alias /templates/x.html;
    }
     location / {
        root /templates;
        index index.html;
    }
}

location = /x是精确匹配规则,只会响应domain.com/x这个请求,直接返回指定的x.html文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:05:24