如何根据HTTP请求的Accept头设置Nginx的autoindex_format参数?
问题原因
Nginx的autoindex_format指令不支持使用变量——这个指令属于启动时就会解析的配置阶段指令,而变量是请求处理阶段才会动态赋值的,直接将变量传入会触发语法错误。
正确配置方法
可以通过内部跳转的方式实现:先通过map根据Accept头匹配出对应的格式类型,然后在主location中根据变量值跳转到不同的内部location,每个内部location单独设置对应的autoindex_format值。
完整配置示例:
http { # 根据Accept头映射格式类型 map $http_accept $autoindex_type { default html; ~*json json; # 用~*忽略大小写匹配 ~*xml xml; } server { ... # 主访问入口 location / { root /usr/share/nginx/files; autoindex on; # 根据匹配结果跳转到对应内部处理location if ($autoindex_type = json) { rewrite ^ /_autoindex_json$uri last; } if ($autoindex_type = xml) { rewrite ^ /_autoindex_xml$uri last; } # 默认使用html格式 autoindex_format html; } # 内部处理json格式的索引 location ^~ /_autoindex_json { internal; # 仅允许内部跳转访问 root /usr/share/nginx/files; autoindex on; autoindex_format json; # 去除前缀,还原原始请求路径 rewrite ^/_autoindex_json(.*)$ $1 break; } # 内部处理xml格式的索引 location ^~ /_autoindex_xml { internal; root /usr/share/nginx/files; autoindex on; autoindex_format xml; rewrite ^/_autoindex_xml(.*)$ $1 break; } } }
补充说明
- 使用
~*修饰符可以忽略Accept头中字符串的大小写,适配application/json、Application/JSON等不同格式的请求头。 internal指令确保这些内部location不会被外部直接访问,仅通过内部跳转触发。- 内部location中的
rewrite用于去除跳转时添加的前缀,保证访问的文件路径正确。
内容的提问来源于stack exchange,提问作者Pavel
相关产品推荐
相关产品推荐

