Nginx从$uri提取文件扩展名并映射Content-Type问题求助
Nginx配置:正确提取文件扩展名并映射Content-Type
核心问题修复
第一个map无法提取扩展名的原因是正则表达式未设置捕获组,导致$1为空值,无法匹配后续map中的扩展名键。修改后的第一个map如下:
map $uri $file_extension { default "extension not found..."; ~*(\.[0-9a-z]+)$ $1; }
~*:开启不区分大小写匹配,适配.HTML、.CSS这类大写扩展名场景(\.[0-9a-z]+)$:通过捕获组完整提取URI末尾的带点扩展名(如.html、.js),并赋值给$file_extension
调试头缺失修复
Nginx的add_header指令默认仅在2xx/3xx响应中添加头部,若需要在所有状态码下查看调试头,需追加always参数:
location ~ /middle/path/.*\.(html|txt|md|css|js|jpg|jpeg|png)$ { proxy_hide_header Content-Type; add_header x-file-extension "$file_extension" always; add_header x-new-content-type "$new_content_type" always; add_header Content-Type $new_content_type always; }
可选优化:统一扩展名大小写
如果需要兼容大小写混合的扩展名(如.Html),可以在第一个map中将捕获的扩展名转为小写,确保能匹配第二个map中的小写键:
map $uri $file_extension { default "extension not found..."; ~*\.([0-9a-z]+)$ ".$lowercase($1)"; }
内容的提问来源于stack exchange,提问作者Artem Sharipov
相关产品推荐
相关产品推荐

