Nginx实现多语言静态目录有三种方案:一是用map+root按子域名映射语言根目录;二是用正则location+try_files按URL路径前缀查找对应子目录;三是为各语言路径单独配置location+alias。

Linux Nginx 用 root 指令配置多语言静态目录,核心是让不同语言路径(如 /zh/、/en/)对应各自独立的文件系统目录(如 /var/www/myapp/zh/、/var/www/myapp/en/)。但要注意:root 本身不支持动态拼接语言名,必须借助 map 预定义变量或用 location + 正则 + try_files 组合实现路径映射。
方案一:用 map + root 实现域名级多语言(推荐)
适合每种语言使用独立子域名(如 zh.example.com、en.example.com)的场景。在 http 块中提前映射 Host 到语言根目录:
- 在
nginx.conf的http{...}区域开头添加:
map $host $lang_root {
default /var/www/myapp/en;
~^zh\.example\.com$ /var/www/myapp/zh;
~^en\.example\.com$ /var/www/myapp/en;
~^ja\.example\.com$ /var/www/myapp/ja;
}
- 在
server块中引用该变量:
server {
listen 80;
server_name example.com zh.example.com en.example.com ja.example.com;
location / {
root $lang_root;
index index.html;
try_files $uri $uri/ =404;
}
}
访问 zh.example.com/about 时,Nginx 查找 /var/www/myapp/zh/about;en.example.com/about 则查 /var/www/myapp/en/about。
Linux 性能分析与调优专家,覆盖 CPU、内存、磁盘 I/O、网络、内核参数、编译优化、容器/K8s。适用场景:系统卡顿/高负载、内存不足/OOM/Swap 高、CPU 异常/iowait 高。
方案二:用正则 location + try_files 实现路径级多语言
适合所有语言共用一个域名、靠 URL 路径区分(如 example.com/zh/、example.com/en/)的情况。此时 root 固定,靠 try_files 按语言前缀查找对应子目录:
- 确保磁盘结构为:
/var/www/myapp/zh/、/var/www/myapp/en/、/var/www/myapp/ja/ - 配置示例:
location ~ ^/(?<lang>zh|en|ja)(?:/(.*))?$ {
root /var/www/myapp;
try_files /$lang/$2 /$lang/$2/index.html =404;
}
说明:
– 请求 /zh/contact → 查 /var/www/myapp/zh/contact
– 请求 /en/ → 查 /var/www/myapp/en/index.html
– 注意:该写法要求每个语言目录下都有完整站点结构(含 index.html)
方案三:多个 location 块 + 固定 root(简单直接)
适用于语言种类少、路径明确的场景。为每个语言路径单独写 location,显式指定 root:
location /zh/ {
alias /var/www/myapp/zh/;
index index.html;
try_files $uri $uri/ /zh/index.html;
}
location /en/ {
alias /var/www/myapp/en/;
index index.html;
try_files $uri $uri/ /en/index.html;
}
⚠️注意:
– 这里用了 alias 而非 root,因为 location /zh/ 匹配的是带前缀的 URI,用 alias 可避免重复拼接 /zh/;
– 若坚持用 root,需把 root 设为 /var/www/myapp,并确保请求 /zh/about 时,文件实际位于 /var/www/myapp/zh/about(即目录结构要匹配 URI)
关键注意事项
-
root必须写绝对路径,结尾不强制加斜杠(/var/www/myapp和/var/www/myapp/效果一致) - Nginx 工作进程用户(如
www-data或nginx)需对各语言目录有读取权限 -
map指令只能出现在http块,不能放在server或location内 - 若启用
index,记得配合try_files或确保目标目录下存在对应首页文件 - 避免在
location /中用alias,应优先用root;而子路径(如/zh/)更适合alias

















