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

NGINX多语言静态站点配置问题:/de路径404及自定义路径失效

解决NGINX部署HUGO多语言站点的404与默认语言问题

问题诊断

你的NGINX配置存在两个核心问题:

  1. 语法错误:所有root指令末尾缺少分号,这会导致NGINX配置加载异常(即使部分路径能访问,也是侥幸)。
  2. 路径匹配逻辑错误:当使用location /de/时,若设置root /usr/share/nginx/html/my-app/de,NGINX会将请求URI与root拼接,最终寻找的路径是/usr/share/nginx/html/my-app/de/de/xxx.html,这显然与你的实际文件结构不符,直接导致404。

修正后的配置方案

以下配置可解决所有问题,同时兼顾默认语言、指定语言路径和自定义路径的适配:

http {
    ...
    server {
        listen                8080;
        server_name           localhost;
        index                 index.html;
        # 默认根目录指向en语言文件
        root                  /usr/share/nginx/html/my-app/en;

        # 处理根路径请求,直接返回en内容
        location / {
            try_files      $uri $uri/index.html =404;
        }

        # 处理de语言路径(注意你的实际站点目录是fr,需根据真实目录调整)
        location ^~ /de/ {
            alias           /usr/share/nginx/html/my-app/de/;
            try_files      $uri $uri/index.html =404;
        }

        # 处理en-us路径,映射到en目录
        location ^~ /en-us/ {
            alias           /usr/share/nginx/html/my-app/en/;
            try_files      $uri $uri/index.html =404;
        }

        # 处理任意未定义的语言路径(如/any-lang/),默认返回en内容
        location ~ ^/([a-z-]+)/ {
            rewrite         ^/([a-z-]+)/(.*)$ /$2 break;
            try_files      $uri $uri/index.html =404;
        }
    }
}

关键配置说明

  • alias指令:替代错误的root配置,当请求/de/xxx.html时,会直接映射到/usr/share/nginx/html/my-app/de/xxx.html,完美匹配你的文件结构。
  • 默认语言全局配置:将全局root设为en目录,确保根路径/直接加载en内容。
  • 正则匹配自定义路径:location ~ ^/([a-z-]+)/会匹配所有类似/any-lang/的路径,通过rewrite去掉语言前缀,直接使用en目录下的对应文件。

验证步骤

  1. 检查配置语法:
    sudo nginx -t
    
  2. 重启NGINX生效:
    sudo nginx -s reload
    
  3. 测试以下路径:
    • http://localhost:8080:加载en内容
    • http://localhost:8080/de/:加载de内容(需确保/usr/share/nginx/html/my-app/de/目录存在且有文件)
    • http://localhost:8080/any-lang/xxx.html:加载en目录下的xxx.html

注意:你的站点实际目录是en/和fr/,但配置中写了de/,需根据真实目录调整location /de/中的路径为/usr/share/nginx/html/my-app/fr/。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:52:54