Nginx 最小配置

安全的服務(wù)器是只配置所需內(nèi)容的服務(wù)器。

理想情況下,應(yīng)基于最小配置構(gòu)建服務(wù)器,不要配置多余的選項(xiàng)。

使用最小的配置也有助于調(diào)試。如果錯(cuò)誤在最小配置中,可以通過增加或減少配置來排查錯(cuò)誤。


下面是運(yùn)行 nginx 所需的最低配置:

# /etc/nginx/nginx.conf  
  
events {}         # event context have to be defined to consider config valid  
  
http {  
 server {  
    listen 80;  
    server_name  cainiaoplus.com;
  
    return 200 "Hello";  
  }  
}  

root, location 和 try_files 指令

root 指令

root 指令用于設(shè)置請(qǐng)求的根目錄,允許 nginx 將傳入的請(qǐng)求映射到文件系統(tǒng)。

server {  
  listen 80;  
  server_name cainiaoplus.com;
  root /var/www/cainiaoplus.com;
} 

它允許nginx根據(jù)請(qǐng)求返回服務(wù)器內(nèi)容:

cainiaoplus.com/index.html     # returns /var/www/cainiaoplus.com/index.html
cainiaoplus.com/foo/index.html # returns /var/www/cainiaoplus.com/foo/index.html  
 

Location 指令

location 指令用于根據(jù)請(qǐng)求的 URI(統(tǒng)一資源標(biāo)識(shí)符)設(shè)置配置。

語法是:

location [modifier] path  

例子:

location /foo {  
  # ...  
}  

當(dāng)沒有給出修飾符時(shí),路徑被視為前綴,之后可以跟任何東西。上面的例子將匹配:

/foo  
/fooo  
/foo123  
/foo/bar/index.html  
... 

我們還可以在給定的上下文中使用多個(gè)位置指令:

server {  
  listen 80;  
  server_name cainiaoplus.com;
  root /var/www/cainiaoplus.com;
  
  location / {  
    return 200 "root";  
  }  
  
  location /foo {  
    return 200 "foo";  
  }  
}  

cainiaoplus.com/       # => "root"
cainiaoplus.com/foo    # => "foo"
cainiaoplus.com/foo123 # => "foo"
cainiaoplus.com/bar    # => "root"

Nginx 還提供了一些可以與location指令結(jié)合使用的修飾符。

修飾符已分配優(yōu)先級(jí):

=           - 完全匹配  
^~          - 優(yōu)先匹配  
~ && ~*     - 正則表達(dá)式匹配  
no modifier - 前綴匹配  

首先,nginx 將檢查是否有任何完全匹配。如果它不存在,它將尋找優(yōu)先的。如果此匹配也失敗,則將按出現(xiàn)順序測(cè)試正則表達(dá)式匹配。如果都失敗了,將使用最后一個(gè)前綴匹配。

location /match {  
  return 200 'Prefix match: will match everything that starting with /match';  
}  
  
location ~* /match[0-9] {  
  return 200 'Case insensitive regex match';  
}  
  
location ~ /MATCH[0-9] {  
  return 200 'Case sensitive regex match';  
}  
  
location ^~ /match0 {  
  return 200 'Preferential match';  
}  
  
location = /match {  
  return 200 'Exact match';  
} 
 
/match # =>  '完全匹配'  
/match0 # =>  '優(yōu)先匹配'  
/match1 # =>  '不區(qū)分大小寫的正則表達(dá)式匹配'  
/MATCH1 # =>  '區(qū)分大小寫的正則表達(dá)式匹配'  
/match-abc # =>  '前綴匹配:匹配以 /match 開頭的所有內(nèi)容' 

try_files 指令

該指令嘗試不同的路徑,并將返回找到的任何一個(gè)。

try_files $uri index.html =404;  

所以 /foo.html 將嘗試按以下順序返回文件:

  • $uri (/foo.html);
  • index.html
  • If none is found:404

如果我們?cè)诜?wù)器上下文中定義 try_files,然后定義一個(gè)查找所有請(qǐng)求的blocation,我們的 try_files 將不會(huì)被執(zhí)行。發(fā)生這種情況是因?yàn)榉?wù)器上下文中的 try_files 定義了偽 location,這是可能的最不具體的 location。因此,定義 location / 將比偽 location 更具體。

server {  
  try_files $uri /index.html =404;  
  
  location / {  
  }  
}  

因此,我們應(yīng)該避免在服務(wù)器上下文中使用 try_files:

server {  
  location / {  
    try_files $uri /index.html =404;  
  }  
}  
丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清