Linux&&nginx服務配置文件詳解

參考資料:
https://mp.weixin.qq.com/s/X6ijfWwQ_ANQLSIx3As3cg
https://mp.weixin.qq.com/s/Rvf_YSItpCFQcq7Wt-wviQ

nginx服務的構成

基本的 nginx 體系結構由 master 進程和其 worker 進程組成。
master 讀取配置文件,並維護 worker 進程
worker 則會對請求進行實際處理。

使用信號管理nginx

  • stop - 快速關閉
  • quit - 優雅關閉(等待worker線程完成處理)
  • reload - 重載配置文件
  • reopen - 重新打開日誌文件

nginx.conf

rewrite

server {
  rewrite ^ /foobar;
 
  location /foobar {
    rewrite ^ /foo;
    rewrite ^ /bar;
  }
}

以訪問/sample爲例,用戶的訪問流程:

  • server的rewrite將會執行,從 /sample rewrite 到 /foobar
  • location /foobar 會被匹配
  • location的第一個rewrite執行,從/foobar rewrite到/foo
  • location的第二個rewrite執行,從/foo rewrite到/bar

return

server {
  location / {
    return 200;
    return 404;
  }
}

在上述的情況下,立即返回200。

server {}

在 Nginx 內部,你可以指定多個虛擬服務器,每個虛擬服務器用 server{} 上下文描述。

server {
  listen      *:80 default_server;
  server_name netguru.co;
 
  return 200 "Hello from netguru.co";
}
 
server {
  listen      *:80;
  server_name foo.co;
 
  return 200 "Hello from foo.co";
}
 
server {
  listen      *:81;
  server_name bar.co;
 
  return 200 "Hello from bar.co";
}

這將告訴 Nginx 如何處理到來的請求。Nginx 將會首先通過檢查 listen 指令來測試哪一個虛擬主機在監聽給定的 IP 端口組合。

然後,server_name 指令的值將檢測 Host 頭(存儲着主機域名)。
Nginx 將會按照下列順序選擇虛擬主機:

  • 匹配sever_name指令的IP-端口主機
  • 擁有default_server標記的IP-端口主機
  • 首先定義的IP-端口主機
  • 如果沒有匹配,拒絕連接。
#基於上述環境的測試及返回結果
Request to foo.co:80     => "Hello from foo.co"
Request to www.foo.co:80 => "Hello from netguru.co"
Request to bar.co:80     => "Hello from netguru.co"
Request to bar.co:81     => "Hello from bar.co"
Request to foo.co:81     => "Hello from bar.co"

server_name

server_name指令接受多個值。它還處理通配符匹配和正則表達式。

server_name netguru.co www.netguru.co; # exact match
server_name *.netguru.co;              # wildcard matching
server_name netguru.*;                 # wildcard matching
server_name  ~^[0-9]*\.netguru\.co$;   # regexp matching

當有歧義時,nginx 將使用下面的命令:

  • 確切的名字
  • 最長的通配符名稱以星號開始,例如“* .example.org”。
  • 最長的通配符名稱以星號結尾,例如“mail.**”
  • 首先匹配正則表達式(按照配置文件中的順序)

Nginx 會存儲 3 個哈希表:確切的名字,以星號開始的通配符,和以星號結尾的通配符。如果結果不在任何表中,則將按順序進行正則表達式測試。

值得謹記的是:

server_name .netguru.co;

等同於:

server_name  netguru.co  www.netguru.co  *.netguru.co;

有一點不同,.netguru.co 存儲在第二張表,這意味着它比顯式聲明的慢一點。

listen

在很多情況下,能夠找到 listen 指令,接受IP:端口值

listen 127.0.0.1:80;
listen 127.0.0.1;    # by default port :80 is used
 
listen *:81;
listen 81;           # by default all ips are used
 
listen [::]:80;      # IPv6 addresses
listen [::1];        # IPv6 addresses

然而,還可以指定 UNIX-domain 套接字

listen unix:/var/run/nginx.sock;

你甚至可以使用主機名

listen localhost:80;
listen netguru.co:80;

但請慎用,由於主機可能無法啓動 nginx,導致無法綁定在特定的 TCP Socket。
最後,如果指令不存在,則使用 *:80。

root

root 指令設置請求的根目錄,允許 nginx 將傳入請求映射到文件系統。

server {
  listen 80;
  server_name netguru.co;
  root /var/www/netguru.co;
}

根據給定的請求,指定 nginx 服務器允許的內容

netguru.co:80/index.html     # returns /var/www/netguru.co/index.html
netguru.co:80/foo/index.html # returns /var/www/netguru.co/foo/index.html

location

location指令根據請求的 URI 來設置配置。

location [modifier] path

location /foo/ {
  # ...
}

如果沒有指定修飾符,則路徑被視爲前綴,其後可以跟隨任何東西。

以上例子將匹配

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

此外,在給定的上下文中可以使用多個 location 指令。

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

基於上述環境的測試及返回:

netguru.co:80   /       # => "root"
netguru.co:80   /foo    # => "foo"
netguru.co:80   /foo123 # => "foo"
netguru.co:80   /bar    # => "root"

Nginx 也提供了一些修飾符,可用於連接 location。這些修飾符將影響 location 模塊使用的地方,因爲每個修飾符都分配了優先級。

=           - Exact match
^~          - Preferential match
~ && ~*     - Regex match
no modifier - Prefix match

Nginx 會先檢查精確匹配。如果找不到,我們會找優先級最高的。如果這個匹配依然失敗,正則表達式匹配將按照出現的順序進行測試。至少,最後一個前綴匹配將被使用。

location /match {
  return 200 'Prefix match: matches 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/    # => 'Exact match'
/match0    # => 'Preferential match'
/match1    # => 'Case insensitive regex match'
/MATCH1    # => 'Case sensitive regex match'
/match-abc # => 'Prefix match: matches everything that starting with /match'

try_files

嘗試不同的路徑,找到一個路徑就返回。

try_files $uri index.html =404;

所以對於 /foo.html 請求,它將嘗試按以下順序返回文件

  • $uri ( /foo.html )
  • index.html
  • 如果什麼都沒找到則返回 404

有趣的是,如果我們在服務器上下文中定義 try_files,然後定義匹配的所有請求的 location —— try_files 將不會執行。

這是因爲在服務器上下文中定義的 try_files 是它的 pseudo-location,這是最不可能的位置。因此,定義 location/ 將比 pseudo-location 更具體。

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

因此,你應該避免在 server 上下文中出現 try_files:

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

配置作用總覽

#定義Nginx運行的用戶和用戶組
user www www;
 
#nginx進程數,建議設置爲等於CPU總核心數。
worker_processes 8;
 
#全局錯誤日誌定義類型,[ debug | info | notice | warn | error | crit ]
error_log /var/log/nginx/error.log info;
 
#進程文件
pid /var/run/nginx.pid;
 
#一個nginx進程打開的最多文件描述符數目,理論值應該是最多打開文件數(系統的值ulimit -n)與nginx進程數相除,但是nginx分配請求並不均勻,所以建議與ulimit -n的值保持一致。
worker_rlimit_nofile 65535;
 
#工作模式與連接數上限
events
{
#參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
use epoll;
#單個進程最大連接數(最大連接數=連接數*進程數)
worker_connections 65535;
}
 
#設定http服務器
http
{
include mime.types; #文件擴展名與文件類型映射表
default_type application/octet-stream; #默認文件類型
#charset utf-8; #默認編碼
server_names_hash_bucket_size 128; #服務器名字的hash表大小
client_header_buffer_size 32k; #上傳文件大小限制
large_client_header_buffers 4 64k; #設定請求緩
client_max_body_size 8m; #設定請求緩
sendfile on; #開啓高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,對於普通應用設爲 on,如果用來進行下載等應用磁盤IO重負載應用,可設置爲off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。
autoindex on; #開啓目錄列表訪問,合適下載服務器,默認關閉。
tcp_nopush on; #防止網絡阻塞
tcp_nodelay on; #防止網絡阻塞
keepalive_timeout 120; #長連接超時時間,單位是秒
 
#FastCGI相關參數是爲了改善網站的性能:減少資源佔用,提高訪問速度。下面參數看字面意思都能理解。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
 
#gzip模塊設置
gzip on; #開啓gzip壓縮輸出
gzip_min_length 1k; #最小壓縮文件大小
gzip_buffers 4 16k; #壓縮緩衝區
gzip_http_version 1.0; #壓縮版本(默認1.1,前端如果是squid2.5請使用1.0)
gzip_comp_level 2; #壓縮等級
gzip_types text/plain application/x-javascript text/css application/xml;
#壓縮類型,默認就已經包含text/html,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
gzip_vary on;
#limit_zone crawler $binary_remote_addr 10m; #開啓限制IP連接數的時候需要使用
 
upstream blog.ha97.com {
#upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的機率越大。
server 192.168.80.121:80 weight=3;
server 192.168.80.122:80 weight=2;
server 192.168.80.123:80 weight=3;
}
 
#虛擬主機的配置
server
{
    #監聽端口
    listen 80;
    #域名可以有多個,用空格隔開
    server_name www.ha97.com ha97.com;
    index index.html index.htm index.php;
    root /data/www/ha97;
    location ~ .*\.(php|php5)?$
    {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi.conf;
    }
    #圖片緩存時間設置
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
    expires 10d;
    }
    #JS和CSS緩存時間設置
    location ~ .*\.(js|css)?$
    {
    expires 1h;
    }
    #日誌格式設定
    log_format access '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" $http_x_forwarded_for';
    #定義本虛擬主機的訪問日誌
    access_log /var/log/nginx/ha97access.log access;
 
    #對 "/" 啓用反向代理
    location / {
    proxy_pass http://127.0.0.1:88;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    #後端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #以下是一些反向代理的配置,可選。
    proxy_set_header Host $host;
    client_max_body_size 10m; #允許客戶端請求的最大單文件字節數
    client_body_buffer_size 128k; #緩衝區代理緩衝用戶端請求的最大字節數,
    proxy_connect_timeout 90; #nginx跟後端服務器連接超時時間(代理連接超時)
    proxy_send_timeout 90; #後端服務器數據回傳時間(代理髮送超時)
    proxy_read_timeout 90; #連接成功後,後端服務器響應時間(代理接收超時)
    proxy_buffer_size 4k; #設置代理服務器(nginx)保存用戶頭信息的緩衝區大小
    proxy_buffers 4 32k; #proxy_buffers緩衝區,網頁平均在32k以下的設置
    proxy_busy_buffers_size 64k; #高負荷下緩衝大小(proxy_buffers*2)
    proxy_temp_file_write_size 64k;
    #設定緩存文件夾大小,大於這個值,將從upstream服務器傳
    }
 
    #設定查看Nginx狀態的地址
    location /NginxStatus {
    stub_status on;
    access_log on;
    auth_basic "NginxStatus";
    auth_basic_user_file conf/htpasswd;
    #htpasswd文件的內容可以用apache提供的htpasswd工具來產生。
    }
 
    #本地動靜分離反向代理配置
    #所有jsp的頁面均交由tomcat或resin處理
    location ~ .(jsp|jspx|do)?$ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
    }
    #所有靜態文件由nginx直接讀取不經過tomcat或resin
    location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
    { expires 15d; }
    location ~ .*.(js|css)?$
    { expires 1h; }
}
}

最小化配置

# /etc/nginx/nginx.conf
 
events {}                   # events context needs to be defined to consider config valid
 
http {
 server {
    listen 80;
    server_name  netguru.co  www.netguru.co  *.netguru.co;
 
    return 200 "Hello";
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章