NGINX如何用单个map实现响应码与对应标题、描述的关联映射
NGINX如何用单个map实现响应码与对应标题、描述的关联映射
嗨,我来帮你搞定这个问题!NGINX的map指令本身确实不支持直接存储多值键值对,但我们可以用个小技巧——把标题和描述拼接成单个字符串,再拆分出对应的变量,这样就能用一个map搞定所有状态码的映射啦,维护起来比两个map方便多了。
下面是具体的实现步骤:
1. 定义单个组合映射
在NGINX配置的http块里,创建一个map,把每个状态码映射成「标题|描述」格式的字符串(这里用|作为分隔符,你可以换成任何不会在标题/描述里出现的特殊字符):
map $status $status_combined { # 默认值,匹配未定义的状态码 default "Something is wrong|An unexpected error occurred."; # 逐个定义需要的状态码 400 "Bad Request|The server cannot or will not process the request due to something that is perceived to be a client error."; 401 "Unauthorized|The client must authenticate itself to get the requested response."; 403 "Forbidden|You don't have permission to access this resource."; 404 "Not Found|The requested resource could not be found."; 500 "Internal Server Error|The server encountered an unexpected condition that prevented it from fulfilling the request."; # 其他状态码按需添加即可 }
2. 拆分组合字符串为独立变量
同样在http块里,通过正则捕获把组合字符串拆分成$status_title和$status_desc两个变量,这样SSI就能直接调用它们了:
# 先初始化变量为空,避免未匹配时出现异常 set $status_title ""; set $status_desc ""; # 用正则匹配分隔符,拆分出标题和描述 if ($status_combined ~* "^([^|]+)\|(.+)$") { set $status_title $1; set $status_desc $2; }
3. 配置错误页面与SSI
确保你的错误页面配置正确,并且开启了SSI功能,比如:
# 指定错误页面路径 error_page 400 401 403 404 500 /error.html; location = /error.html { root /path/to/your/static/files; # 替换成你实际的静态文件目录 ssi on; # 开启SSI支持 }
4. 错误页面的SSI调用
你的error.html里的代码可以保持和原来一样,直接调用拆分后的变量:
<h1><!--# echo var="status" default="" --> <!--# echo var="status_title" default="Something is wrong" --></h1> <p align="center"><!--# echo var="status_desc" default="" --></p>
这样配置后,你只需要维护这一个map就可以管理所有状态码的标题和描述了,而且变量能正常被SSI读取显示。之前两个map没生效的原因大概率是变量作用域的问题(比如map定义的位置不对,导致错误页面的location无法获取到变量),用这种组合拆分的方式能有效避免这类问题。
备注:内容来源于stack exchange,提问作者Jaume Sabater
相关产品推荐
相关产品推荐

