<aside> 💭 DISCUSSION 大家可以回家研究看看 location / 這段是在做什麼,未來使用 Framework 也會有不同的設定。

</aside>

server {
        listen 80;
        listen [::]:80;

        root /var/www/localhost/public;
        index index.html index.htm index.nginx-debian.html;

        server_name localhost www.localhost;

        location / {
                try_files $uri $uri/ =404;
        }
}

location block and server block

首先,簡略說明一下 server block 和 location block

Nginx logically divides the configurations meant to serve different content into blocks, which live in a hierarchical structure. Each time a client request is made, Nginx begins a process of determining which configuration blocks should be used to handle the request.

The main blocks that we will be discussing are the server block and the location block.

A server block is a subset of Nginx’s configuration that defines a virtual server used to handle requests of a defined type. Administrators often configure multiple server blocks and decide which block should handle which connection based on the requested domain name, port, and IP address.

A location block lives within a server block and is used to define how Nginx should handle requests for different resources and URIs for the parent server. The URI space can be subdivided in whatever way the administrator likes using these blocks. It is an extremely flexible model.

Nginx 的 configuration 有分成數個 block,在 user 發出 request 時,Nginx 會根據一套演算法,選擇要執行哪個 block 裡面的 code。

主要的 Block 分成 Server Block 和 Location block。

Server Block 可以定義一個 virtual server,當有 connection request 送來時,根據 requested domain name, port, and IP address ,以及 virtual server 中的 listenserver_name 等設定,決定要用哪一個 server block 回應 connection request。

Location block 會被放在 Server Block 底下(或者在某些條件下,在 location block 底下),決定對該 server 提出的 resource 或 URI 的 request 要怎麼 handle。

Location block syntax

location optional_modifier location_match {
		# code here
}

location_match 是要 match 的路徑,當 request 的 resource 所在的 location 和 location_match match 時,就會執行該 block 內的 code

optional_modifier 則是指定了 match 的方式:

一個 request location 可能會同時 match 到很多 location block,Nginx 有一套演算法決定要選用哪一個 match 的 block。這裡不詳細講,大略來說:

  1. 先對於所有 non-regular expression match,找完全匹配的 match,再來找 longest-prefix match。
  2. 把 1. 的結果存下來,對於所有 regular expression match,由上到下,在 1. 中找到的 location 底下做 regular expression match。
  3. 在 2. 中第一個 match 的 block 即被選中,如果一個都找不到,則選 1. 中找到的 block

在這個 example 中

location / 

代表了對於所有包含 / 作為 prefix 的 request location 都有機會執行到這個 block。

/ 其實就代表了這個 server block 底下的 web root,所以所有路徑都能 match 到這個 block。而在 longest prefix match 的邏輯底下,這也是優先度最低的 match。