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

Nginx try_files忽略实际存在文件:临时目录文件服务配置异常

问题:Nginx location配置无法正确提供/tmp下非.txt文件服务

我正尝试配置一个Nginx location块,用于从/tmp目录提供文件服务,但仅允许访问非.txt后缀的文件。当前配置如下:

location ~^\/temporary(?!.*\.txt$)(.*)$ {
        root /tmp;
        try_files $1 =404;
}

问题在于,即便请求的文件实际存在,我仍只能收到404响应。调试请求/temporary/test.html时的日志显示:

022/07/17 19:53:42 [debug] 6408#0: *1 http script capture: "/test.html"                                                                                                     
2022/07/17 19:53:42 [debug] 6408#0: *1 trying to use file: "/test.html" "/tmp/test.html"                                                                                     
2022/07/17 19:53:42 [debug] 6408#0: *1 trying to use file: "=404" "/tmp=404"                                                                                                   
2022/07/17 19:53:42 [debug] 6408#0: *1 http finalize request: 404, "/temporary/test.html?" a:1, c:1                                                                            
2022/07/17 19:53:42 [debug] 6408#0: *1 http special response: 404, "/temporary/test.html?"                                                                                     
2022/07/17 19:53:42 [debug] 6408#0: *1 http set discard body
2022/07/17 19:53:42 [debug] 6408#0: *1 HTTP/1.1 404 Not Found

日志显示路径拼接正确,但服务器返回404。同时已确认文件存在且Nginx运行用户nobody有读取权限:

sudo -u nobody stat /tmp/test.html
  File: /tmp/test.html
  Size: 15              Blocks: 8          IO Block: 4096   regular file
Device: 803h/2051d      Inode: 2097220     Links: 1
Access: (0664/-rw-rw-r--)  Uid: ( 1000/    nobody)   Gid: ( 1000/    user)
Access: 2022-07-17 19:26:19.701542983 +0300
Modify: 2022-07-17 19:53:17.923305174 +0300
Change: 2022-07-17 19:53:17.923305174 +0300
 Birth: 2022-07-17 19:26:19.701542983 +0300
解决方案

1. 核心问题:SELinux限制

多数情况下,这种文件存在但Nginx返回404的问题是SELinux策略阻止了Nginx访问/tmp目录。默认SELinux会限制Nginx只能访问指定安全上下文的目录(如/usr/share/nginx/html),/tmp目录的安全上下文不符合要求,导致Nginx无法读取文件。

可以通过以下命令临时关闭SELinux验证:

setenforce 0

如果此时请求能正常返回文件,说明SELinux是问题根源。可以通过以下命令永久调整SELinux策略,允许Nginx访问/tmp目录:

setsebool -P httpd_read_user_content 1

或者为/tmp下的文件添加正确的安全上下文:

chcon -Rt httpd_sys_content_t /tmp/

2. 优化Nginx配置(可选)

原有的正则表达式写法过于复杂,建议拆分配置,更清晰且易维护:

# 拒绝所有.txt文件请求
location ~ ^/temporary/.*\.txt$ {
    return 403;
}

# 处理非.txt文件请求,从/tmp提供服务
location ^~ /temporary/ {
    root /tmp;
    rewrite ^/temporary/(.*)$ /$1 break;
    try_files $uri =404;
}

或者使用alias替代root,避免rewrite:

location ^~ /temporary/ {
    alias /tmp/;
    try_files $uri =404;
    # 拒绝.txt文件
    if ($uri ~* \.txt$) {
        return 403;
    }
}

补充说明

  • 使用^~可以让这个location优先于正则匹配的location,避免冲突。
  • 拒绝.txt文件时用return 403比让其404更清晰,明确告知用户无访问权限。

内容的提问来源于stack exchange,提问作者raphael.oester

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:06:24