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

Nginx配置求助:如何通过新location访问gallery目录内容?

问题解决:通过不同Nginx Location访问同一目录内容

问题根源

你之前的/new Location配置错误在于:rewrite指令的目标应该是URI路径,而非直接拼接文件系统路径。当你使用$document_root/gallery/$1作为rewrite目标时,Nginx会把这个字符串当作URI,再结合全局root(/usr/share/nginx/files)去拼接最终文件路径,结果变成了/usr/share/nginx/files/usr/share/nginx/files/gallery/xxx.jpg,显然不存在,因此报错。

正确配置方案

方案1:Rewrite后重匹配Location

利用last标志让Nginx重新匹配Location,复用已有的/gallery配置逻辑:

location /new {
    rewrite "^/new/[A-Za-z0-9]{8}/([0-9]{1,4}\.jpg)$" /gallery/$1 last;
    autoindex on; # 若需要/new路径的目录索引可保留,否则可移除
}
  • 原理:将/new/xxxxxxxxx/1234.jpg格式的请求重写为/gallery/1234.jpg,last标志会让Nginx重新发起一次请求匹配,最终由/gallery Location或全局root找到对应文件。

方案2:使用Alias映射目录

直接将/new路径映射到gallery目录,再清理URI中的多余部分:

location /new {
    alias /usr/share/nginx/files/gallery;
    rewrite "^/new/[A-Za-z0-9]{8}/([0-9]{1,4}\.jpg)$" /$1 break;
    autoindex on;
}
  • 原理:alias将/new路径的根指向/usr/share/nginx/files/gallery,rewrite把/new/xxxxxxxxx/1234.jpg简化为/1234.jpg,结合alias后实际访问的文件路径就是/usr/share/nginx/files/gallery/1234.jpg,break标志停止后续rewrite处理,直接返回文件。

方案3:正则Location直接匹配(简洁版)

如果不需要/new路径的目录索引,可直接用正则Location匹配请求并定位文件:

location ~ ^/new/[A-Za-z0-9]{8}/([0-9]{1,4}\.jpg)$ {
    root /usr/share/nginx/files;
    try_files /gallery/$1 =404;
}
  • 原理:正则匹配目标请求,try_files直接检查/usr/share/nginx/files/gallery/$1是否存在,存在则返回,否则返回404。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 15:30:03