nginx map指令:为什么只允许在http级别使用? [英] nginx map directive: why is it allowed only on http level?

查看:52
本文介绍了nginx map指令:为什么只允许在http级别使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Nginx map 中有一个非常有用的指令.

There is a very useful directive in Nginx map.

,但是只能在 http 级别上使用它(请参阅此处的文档

But it is possible to use it only on the http level (see docs here http://nginx.org/en/docs/http/ngx_http_map_module.html#map).

例如,我定义了一个 server ,并且我想通过 $ url 变量在此服务器中使用一些条件重定向.在 server 内使用此指令非常方便,但不可能.为什么?

For example, I have a server defined and I would like to use some conditional redirects in this server using $url variable. It would be very handy to use this directive inside server but it is not possible. Why?

是的,我也可以在 http 级别上执行此操作,但是在 http 级别上可能定义了不同的 server ,我会希望将这些条件保留在为其定义的 server 部分中.

Yes, I can do it also on the http level but there may be different servers defined on the http level and I would like to keep these conditions inside server section they are defined for.

推荐答案

相当古老的帖子,但我确实想将一些光线带入黑暗中.答案本身很简单.

Pretty old post but I realy want to bring some light into the darkness. The answer itself is quite simple.

DR; TL NGINX中的变量始终是全局变量,一旦定义即可从配置中的任何位置访问.因此,在 server location 块中定义地图没有任何意义.

DR;TL Variables in NGINX are always global and once defined accessable from anywhere in the configration. Therfore it would not make any sense to define a map in a server or location block.

map 创建一个新变量,其值取决于第一个参数中指定的一个或多个源变量的值.

map creates a new variable whose value depends on values of one or more of the source variables specified in the first parameter.

示例配置:

map $host $myvar {
example.com "test";
foo.com     "for";

}

因为NGINX中的变量始终是全局变量,并且一旦定义就可以在配置中的任何其他位置使用.因此,将地图移至某个位置或服务器块没有任何意义.我们的 map 指令有趣的事实是变量 myvar 何时会收到其值或何时将其赋值?

As variables in NGINX are ALWAYS global and once defined available anywhere else in the configuration. So it wouldn't make any sense to move the map into a location or server block. The interesting fact with our map directive is when the variable myvar will receive its value or when it will be assigned?

在变量将在您的配置中使用后,映射会将该值分配给该变量

这意味着您可以在http上下文中定义地图,但是该值将在您访问nginx配置中的 $ myvar 时分配.

That means you can define the map in the http context but the value will be assigned at the point you are accessing $myvar in your nginx configuration.

回到您的问题:由于NGINX变量始终是全局变量,因此每个 server 块都有一个 map 会很有意义,因为它们无论如何都是全局的.

Back to your question: As NGINX variables are always global having a map per server block would make sense as they would be global anyway.

这篇关于nginx map指令:为什么只允许在http级别使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆