Nginx 配置继承模型

要了解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.
    }
}

当然,它并不那么简单。在位置内有三种可能的上下文,一个嵌套位置,一个if和limit_except。指令的行为实际上完全取决于定义它的模块。如果在该上下文中允许,则所有normal和array指令都将正确继承。对于行动指令,故事有点不同。通常它们不会继承到嵌套位置,但最终取决于模块的预期,并且它可以在指令的基础上有所不同。这里没有使用nginx文档,所以你必须尝试一下,看看nginx是否会抱怨。为了更好地衡量,让我们举一个最常见的行为示例以及它如何影响重写:

server {
    location /calendar {
        rewrite ^ /static.php; # Executes unless inner location matches.
 
        location ~ \.php$ {
            fastcgi_pass backend; # Outer location context rewrite is not executed.    
        }
    }
}

try_files指令与上面提到的每个其他操作指令大致相同,不同之处在于,如果放置在服务器上下文中,nginx实际上会创建一个伪位置,该位置是可能的最不具体的位置。这意味着如果请求与定义的位置匹配,则不会执行try_files指令。这意味着如果您有location / defined,那么您有一个匹配每个可能请求的位置,因此try_files永远不会实际执行。因此,如果可能的话,始终将try_files放在位置上下文而不是服务器上下文中

server {
    try_files $uri /index.php; # This never executes.
 
    location / {
        # Whatever here, or empty.
    }
 
    location ~ \.php$ {
        # If this location executes then try_files still does not execute.
        # Even if location / did not exist.
    }
}

 

关注微信公众号:lovephp

posted @ 2018-07-12 11:58  梦想_行人  阅读(1526)  评论(0编辑  收藏  举报