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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM