请问nginx中$status变量的问题

各位老师,今日准备入门nginx,结果还没入门就栽了一个大跟头T_T
在nginx.conf中有这样一段

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

这里定义了日志的格式,其中$status变量引起了我的注意。
查看access.log日志,我的确也看到了200 404一类的状态码。

我觉得这个变量就很有用了,比如说我代理了一个地址

location / {
    proxy_pass http://127.0.0.1:8000/;
}

我想获得代理的这个地址返回的各种http状态,我就可以通过$status来判断。

但是我尝试返回这个变量时

location / {
    if ($status){
        return $status;
    }
    proxy_pass http://127.0.0.1:8000/;
}

却打印出来了:

invalid return code "$status" in E:nginx/conf/nginx.conf:52

如果我写成:

location / {
    if ($status){
        return 404;
    }
    proxy_pass http://127.0.0.1:8000/;
}

则所有的请求都可以正常返回404,翻了一下nginix文档,在HTTP Core模块中没有发现$status这个变量,那么我想请问下,这个变量是干什么用的?我怎样才可以获取到代理地址返回的状态码?
谢谢~

阅读 6.1k
2 个回答

http core 里有 $status

不过看 nginx 文档,关于return的部分,code 的部分应该是不支持变量的。

另外,nginx 是分不同phase依次执行的,if 在 rewrite phase, proxy_pass 在 content phase, 所以 if 总是先于 proxy_pass 执行的,也就不可能拿到 proxy_pass 的 status code 。

这个location里面是配置路由的啊,location是根据url来进行不同的定位,定位到不同的处理方式上,您这个$status不能当做他匹配的规则吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题