<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;
}
}
首先,簡略說明一下 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 中的 listen 和 server_name 等設定,決定要用哪一個 server block 回應 connection request。
Location block 會被放在 Server Block 底下(或者在某些條件下,在 location block 底下),決定對該 server 提出的 resource 或 URI 的 request 要怎麼 handle。
location optional_modifier location_match {
# code here
}
location_match 是要 match 的路徑,當 request 的 resource 所在的 location 和 location_match match 時,就會執行該 block 內的 code
optional_modifier 則是指定了 match 的方式:
location_match 是 request location 的 prefix,則 match。=: 完全 match~: 將 location_match 當成 case-sensitive regular expression match。~*: 將 location_match 當成 case-insensitive regular expression match。^~: (不是很懂)讓這個 match 的優先度比所有 regular-expression match 還要高。意即,如果排除所有 regular-expression match 後,這個 block 會被 matched,則無視其他所有 regular-expression match。一個 request location 可能會同時 match 到很多 location block,Nginx 有一套演算法決定要選用哪一個 match 的 block。這裡不詳細講,大略來說:
在這個 example 中
location /
代表了對於所有包含 / 作為 prefix 的 request location 都有機會執行到這個 block。
/ 其實就代表了這個 server block 底下的 web root,所以所有路徑都能 match 到這個 block。而在 longest prefix match 的邏輯底下,這也是優先度最低的 match。