首页 > 网站 > Nginx > 正文

详解Nginx如何配置继承模型

2024-08-30 12:24:51
字体:
来源:转载
供稿:网友

要了解nginx的继承模型,首先需要知道nginx使用多个配置块进行操作。 在nginx中,这样的块被称为上下文,例如,放置在服务器上下文中的配置指令驻留在server { }块中,就像放置在http上下文中的指令驻留在http { } 块中一样。

nginx中有6种可能的上下文,这里是从上到下的顺序:

 Global.  Http.  Server.  If.  Location.  Nested Location.  If in location.  limit_except.

默认继承模型是指令仅向下继承。 从来没有侧身,绝对永远不会。 这包括您在内部从一个位置重写请求到另一个位置的情况 - 第一个位置中的每个指令都被遗忘,只有第二个位置指令适用于位置上下文。 在继承行为方面,nginx中有四种类型的配置指令:

  Normal指令 - 每个上下文一个值,例如:“root”或“index”。   Array指令 - 每个上下文有多个值,例如:“access_log”或“fastcgi_param”   Action指令 - 不只是配置的东西,例如:“rewrite”或“fastcgi_pass”   try_files指令。

Normal指令是迄今为止最常见的指令,它遵循默认的继承模型而没有任何意外。 让我们看一个示例配置,显示行为的情况。

server {  root /home/user/public_html;   location /app {    root /usr/share; # This results in /usr/share/app             # Full URI is ALWAYS appended.  }   location /app2 {    // Server context root applies here.  }}

Array指令很像普通指令,因为它们遵循标准继承模型,它始终向下继承并替换在更高上下文中指定的任何指令。 可能令人困惑的是假设你添加到数组。Array 指令的行为是,如果在同一上下文中定义多个指令,则将添加到值,但如果在不同的上下文中定义多个指令,则较低的上下文将替换较高的上下文。 这意味着如果您希望它在多个上下文中存在,您有时需要双重定义一个值。 这种情况的一个例子。

server {  access_log /var/log/nginx/access.log;  include fastcgi.conf;   location ~ ^/calendar/.+/.php$ {    access_log /var/log/nginx/php-requests.log; # If this executes then server context one never does.     fastcgi_param ENV debug; # This *overwrites* the higher context array.    include fastcgi.conf   # Therefore we include it in *this* context again.  }}

Action指令是它开始变得有趣的地方。 它们被限制在一个上下文中并且永远不会向下继承,但是它们可以在多个上下文中指定,并且在某些情况下将针对每个上下文执行。 rewrite指令是一个action指令,允许在服务器和位置上下文中执行两个上下文。

server {  rewrite ^/booking(.*) /calendar$1 permanent; # Always executes.   location /calendar {    rewrite ^ /index.php; # Can execute in addition to and does not replace server context rewrites.  }}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表