1. 程式人生 > >nginx server配置和指令詳解

nginx server配置和指令詳解


Setting Up Virtual Servers



virtual server的配置是放在http模組中,例如:
http {
server {
# Server configuration
}
}
在http中,可以定義多個virtual server以滿足需要
下面的配置表示監聽本機的8000埠:
server {
listen 127.0.0.1:8080;
# The rest of server configuration
}
如果寫明監聽哪個埠,那麼將使用標準埠tcp 80 或預設埠 tcp 8000

在server塊中,可以通過server_name來配置server的多域名,域名可以通過以下方式:
1、完整的域名,如www.example.com
2、帶*號開頭的域名,如 *.example.com
3、帶*號末尾的域名,如 mail.*
4、可匹配的正則表示式



Configuring Locations


下面的配置將匹配以 /some/path/開頭的URIs,例如:/some/path/document.html
location /some/path/ {
...
}

正則表示式能通過 ~ 符號 和 ~* 這兩個符號表示,分別指正則表示式區分大小寫和不區分大小寫,以下例子表示匹配URIs中包含.html 或者.htm 的訪問路徑:
location ~ \.html? {
...
}
nginx會匹配最準確的路徑,會先匹配相對路徑,如果不匹配,再跟正則表示式進行匹配

以下例子中,第一個路徑/images/的檔案目錄是/data,第二個路徑表明nginx作為代理的角色將會把請求轉給後端www.example.com的機器上
server {
location /images/ {
root /data;
}

location / {
proxy_pass http://www.example.com;
}
}

如果這樣配置,那麼除了/image/開頭的URIs,其他的URIs將會以代理的方式傳到後端機器

root 指令
root指令能指定那個目錄作為根目錄用於檔案的檢索,這個指令能用於http,server,location這些塊中
下面的例子指定了virtual server檔案檢索的根目錄:
server {
root /www/data;

location / {
}

location /images/ {
}

location ~ \.(mp3|mp4) {
root /www/media;
}
}
當一個URI以/image/開頭,那麼將會在 /www/data/images/這個目錄下進行檢索;當URI以 .mp3或.mp4結尾時,nginx將會在/www/media目錄下檢索資源

當一個請求以 / 結尾時,nginx會嘗試在該目錄下找到該請求的索引檔案(index file)。預設的索引檔案為index.html。
例如 如果URI為/images/some/path/

,那麼nginx會嘗試查詢/www/data/images/some/path/index.html檔案,如果這個檔案不存在,那麼將預設返回404。
可以通過 autoindex指令來配置nginx自動生成目錄檔案列表,而不是返回index.html
location /images/ {
autoindex on;
}

如果想讓nginx查詢更多指定型別的索引檔案,可以通過Index指令指定,如:
location / {
index index.$geo.html index.htm index.html;
}

try_files 指令
try_files指令會在原請求不存在時,重定向到指定的URI,並返回結果。例如:
server {
root /www/data;

location /images/ {
try_files $uri /images/default.gif;
}
}
/www/data/images/index.html不存在時,將會返回/www/data/images/default.gif檔案

另外一種情況是返回狀態碼:
location / {
try_files $uri $uri/ $uri.html =404;
}