1. 程式人生 > 其它 >Nginx-高階配置學習

Nginx-高階配置學習

server {
  
    listen 80;
  
    server_name localhost;
  
    client_max_body_size 1024M;
  
    location / {               
  
        root e:wwwroot;            //思路:通過/將所有的請求,轉發給root處理
  
        index index.html;
  
    }
  
}   

一.nginx的配置檔案

配置檔案預設為安裝目錄下的conf/nginx.conf,如果有使用到其他子配置檔案,可以在nginx.conf中使用include 檔案路徑;的方式載入使用,比如server段,就可以單獨寫成一個配置檔案,在http段下面使用include載入使用。

...              #全域性塊
 
events {         #events塊
   ...
}
 
http      #http塊
{
    ...   #http全域性塊
    server        #server塊
    { 
        ...       #server全域性塊
        location [PATTERN]   #location塊
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全域性塊
}

1、全域性塊:配置影響nginx全域性的指令。一般有執行nginx伺服器的使用者組,nginx程序pid存放路徑,日誌存放路徑,配置檔案引入,允許生成worker process數等。

2、events塊:配置影響nginx伺服器或與使用者的網路連線。有每個程序的最大連線數,選取哪種事件驅動模型處理連線請求,是否允許同時接受多個網路連線,開啟多個網路連線序列化等。

3、http塊:可以巢狀多個server,配置代理,快取,日誌定義等絕大多數功能和第三方模組的配置。如檔案引入,mime-type定義,日誌自定義,是否使用sendfile傳輸檔案,連線超時時間,單連線請求數等。

4、server塊:配置虛擬主機的相關引數,一個http中可以有多個server。

5、location塊:配置請求的路由,以及各種頁面的處理情況。

########### 每個指令必須有分號結束。#################
#user administrator administrators;  #配置使用者或者組,預設為nobody nobody。
#worker_processes 2;  #允許生成的程序數,預設為1
#pid /nginx/pid/nginx.pid;   #指定nginx程序執行檔案存放地址
error_log log/error.log debug;  #制定日誌路徑,級別。這個設定可以放入全域性塊,http塊,server塊,級別以此為:debug|info|notice|warn|error|crit|alert|emerg
events {
    accept_mutex on;   #設定網路連線序列化,防止驚群現象發生,預設為on
    multi_accept on;  #設定一個程序是否同時接受多個網路連線,預設為off
    #use epoll;      #事件驅動模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大連線數,預設為512
}
http {
    include       mime.types;   #副檔名與檔案型別對映表
    default_type  application/octet-stream; #預設檔案型別,預設為text/plain
    #access_log off; #取消服務日誌   
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定義格式
    access_log log/access.log myFormat;  #combined為日誌格式的預設值
    sendfile on;   #允許sendfile方式傳輸檔案,預設為off,可以在http塊,server塊,location塊。
    sendfile_max_chunk 100k;  #每個程序每次呼叫傳輸數量不能大於設定的值,預設為0,即不設上限。
    keepalive_timeout 65;  #連線超時時間,預設為75s,可以在http,server,location塊。
 # 隱藏nginx版本號,不再瀏覽顯示
    server_tokens off;
#gzip加速
    #gzip  on;
 
    upstream mysvr {  
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #熱備
    }
    error_page 404 https://www.baidu.com; #錯誤頁
    server {
        keepalive_requests 120; #單連線請求上限次數。
        listen       4545;   #監聽埠
        server_name  127.0.0.1;   #監聽地址      
        location  ~*^.+$ {       #請求的url過濾,正則匹配,~為區分大小寫,~*為不區分大小寫。釋義為:不區分大小寫,以1個以上的 非換行符的字元 開始並結束
           #root path;  #根目錄
           #index vv.txt;  #設定預設頁
           proxy_pass  http://mysvr;  #請求轉向mysvr 定義的伺服器列表
           deny 127.0.0.1;  #拒絕的ip
           allow 172.18.5.54; #允許的ip          
        }
    }
}

上面是nginx的基本配置,需要注意的有以下幾點:  

Nginx配置

1、1.$remote_addr 與$http_x_forwarded_for 用以記錄客戶端的ip地址;2.$remote_user :用來記錄客戶端使用者名稱稱; 3.$time_local : 用來記錄訪問時間與時區;4.$request : 用來記錄請求的url與http協議;

  5.$status : 用來記錄請求狀態;成功是200, 6.$body_bytes_s ent :記錄傳送給客戶端檔案主體內容大小;7.$http_referer :用來記錄從那個頁面連結訪問過來的; 8.$http_user_agent :記錄客戶端瀏覽器的相關資訊;

2、驚群現象:一個網路連線到來,多個睡眠的程序被同事叫醒,但只有一個程序能獲得連結,這樣會影響系統性能。

3、每個指令必須有分號結束。

server {
        listen 80;
        server_name score.devops.com;
        # 域名重定向
        rewrite / http://shop.devops.com permanent;
    }
    server {
        listen 80;
        server_name shop.devops.com;
        root html/tp5shop/public;
        
        # gzip on壓縮功能,將伺服器傳輸的檔案壓縮返回給瀏覽器,可以減少傳輸的資料量,提供效能,一般瀏覽器是支援解壓的
        gzip on;    #開啟壓縮功能
        gzip_http_version 1.0;    # 指定http的版本
        gzip_disable 'MSIE [1-6]';    # 禁止IE的1~6版本使用該功能
        gzip_types application/javascript text/css image/jpeg image/png;    # 指定壓縮哪些型別的檔案
        
        # 禁止ip訪問,當有匹配時,就不會在向下匹配
        # deny all;        # 拒絕所有
        # allow 192.168.211.1;         # 允許192.168.211.1
        
        # 使用者訪問限制
        # auth_basic 'pls login:';        # 指定提示語"pls login:"
        # auth_basic_user_file /usr/local/nginx/conf/userlist;        # 指定授權使用者所在檔案
        
        # 基於域名的日誌分割,所有訪問shop.devops.com域名的訪問日誌記錄在該檔案中
        access_log /usr/local/nginx/logs/shop.devops.com shoplog;
        
        
        location / {
            # expires 設定客戶端快取
            #expires 1h;
            index index.php index.html;
            
            # 資源重定向,如訪問http://shop.devops.com/index.html後會被重寫為訪問http://shop.devops.com/index.php,permanent表示永久重定向
            rewrite /index.html /index.php permanent;
            
            # 資源重定向,$request_filename為nginx的內建變數,表示資原始檔路徑
            if (!-e $request_filename) {
                rewrite ^(.*)$ /index.php?s=/$1 last;
                break;
            }
        }
        # 資源重定向
        #location /index {
        #    rewrite /index.html /index.php last;
        #}
        location ~ \.(js|css|jpg|png) {
            # 告訴客戶端所有js,css,jpg,png檔案都可以快取1小時,不用重新在伺服器下載
            expires 1h;
            # 防盜鏈實現,所有不是從shop.devops.com跳轉過去訪問js|css|jpg|png檔案的都被攔截,返回404
            valid_referers shop.devops.com;
            if ($invalid_referer) {
                return 404;
            } 
        }
        # php解析
        location ~ \.php$ {
        #    root           html;
            fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }

location的路由匹配規則

語法規則: location [=|~|~*|^~] /uri/ { … }

  • = 開頭表示精確匹配

  • ^~ 開頭表示uri以某個常規字串開頭,理解為匹配 url路徑即可。nginx不對url做編碼,因此請求為/static/20%/aa,可以被規則^~ /static/ /aa匹配到(注意是空格)。以xx開頭

  • ~ 開頭表示區分大小寫的正則匹配                     以xx結尾

  • ~* 開頭表示不區分大小寫的正則匹配                以xx結尾

  • !~!~*分別為區分大小寫不匹配及不區分大小寫不匹配 的正則

  • / 通用匹配,任何請求都會匹配到。

多個location配置的情況下匹配順序為(參考資料而來,還未實際驗證,試試就知道了,不必拘泥,僅供參考):

 

 

首先精確匹配 =-》其次以xx開頭匹配^~-》然後是按檔案中順序的正則匹配-》最後是交給 / 通用匹配。

當有匹配成功時候,停止匹配,按當前匹配規則處理請求。

例子,有如下匹配規則:

location = / {
   #規則A
}
location = /login {
   #規則B
}
location ^~ /static/ {
   #規則C
}
location ~ \.(gif|jpg|png|js|css)$ {
   #規則D,注意:是根據括號內的大小寫進行匹配。括號內全是小寫,只匹配小寫
}
location ~* \.png$ {
   #規則E
}
location !~ \.xhtml$ {
   #規則F
}
location !~* \.xhtml$ {
   #規則G
}
location / {
   #規則H
} 

nginx的其他配置資訊介紹

三、ReWrite語法

last – 基本上都用這個Flag。
break – 中止Rewirte,不在繼續匹配
redirect – 返回臨時重定向的HTTP狀態302
permanent – 返回永久重定向的HTTP狀態301

1、下面是可以用來判斷的表示式:

-f!-f用來判斷是否存在檔案
-d!-d用來判斷是否存在目錄
-e!-e用來判斷是否存在檔案或目錄
-x!-x用來判斷檔案是否可執行

2、下面是可以用作判斷的全域性變數

例:http://localhost:88/test1/test2/test.php

$host:localhost
$server_port:88
$request_uri:http://localhost:88/test1/test2/test.php $document_uri:/test1/test2/test.php $document_root:D:\nginx/html $request_filename:D:\nginx/html/test1/test2/test.php

  

一些可用的全域性變數

$args
  
$content_length
  
$content_type
  
$document_root
  
$document_uri
  
$host
  
$http_user_agent
  
$http_cookie
  
$limit_rate
  
$request_body_file
  
$request_method
  
$remote_addr
  
$remote_port
  
$remote_user
  
$request_filename
  
$request_uri
  
$query

一些常用的配置

1、普通的(靜態的)http伺服器

這樣如果訪問http://localhost 就會預設訪問到E盤wwwroot目錄下面的index.html,如果一個網站只是靜態頁面的話,那麼就可以通過這種方式來實現部署。

server {
    listen 80;
    server_name localhost;
    client_max_body_size 1024M;
  
    location / {               
        root e:wwwroot;            //思路:通過/將所有的請求,轉發給root處理
        index index.html;
    }  
}   

2、反向代理

localhost的時候,就相當於訪問localhost:8080了

server { 
    listen       80;                                                        
    server_name  localhost;                                              
    client_max_body_size 1024M;
 
    location / {
        proxy_pass http://localhost:8080;  
        proxy_set_header Host $host:$server_port;    //思路:通過/,將所有的請求,轉發給第3方處理
    }
}

既然伺服器可以直接HTTP訪問,為什麼要在中間加上一個反向代理,不是多此一舉嗎?反向代理有什麼作用?

負載均衡、虛擬主機等,都基於反向代理實現,當然反向代理的功能也不僅僅是這些。

3、Redirect(重定向)語法

server {
    listen 80;
    server_name start.igrow.cn;
    index index.html index.php;
    root html;
 
if ($http_host !~ "^star\.igrow\.cn$" {
  rewrite ^(.*) http://star.igrow.cn$1 redirect;
}
 
}

4、防盜鏈

 

 

 

location ~* \.(gif|jpg|png|bmp)$ {
    valid_referers none blocked *.ttlsa.com server_names ~\.google\. ~\.baidu\.;
    if ($invalid_referer) {
        return 403;
        #rewrite ^/ http://www.ttlsa.com/403.jpg;
    }
}

5、根據檔案型別設定過期時間

location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
    if (-f $request_filename) { //只能是檔案,因為這用-f判斷了
        expires 1h;
        break;
    }
}

6、設定圖片快取(過期)時間

 7、禁止訪問某個目錄

location ~* \.(txt|doc)${
    root /data/www/wwwroot/linuxtone/test; #所有使用者都禁止訪問這個目錄
    deny all;
}

8、隱藏版本號的作用

通過你所用的版本,找其漏洞,進行攻擊你

在http中新增該配置:server_tokens off;

alias和root區別

root和alias都可以定義在location模組中,都是用來指定請求資源的真實路徑,比如:

location /i/ {
  root /data/w3;
}

請求  http://foofish.net/i/top.gif  這個地址時,那麼在伺服器裡面對應的真正的資源是  /data/w3/i/top.gif 檔案

注意:真實的路徑是root指定的值加上location指定的值 。

 

而 alias 正如其名,alias指定的路徑是location的別名,不管location的值怎麼寫,資源的 真實路徑都是 alias 指定的路徑 ,比如:

location /i/ {
  alias /data/w3/;
}

同樣請求  http://foofish.net/i/top.gif  時,在伺服器查詢的資源路徑是:  /data/w3/top.gif 

 

其他區別:

    1、 alias 只能作用在location中,而root可以存在server、http和location中。

     2、alias 後面必須要用 “/” 結束,否則會找不到檔案,而 root 則對 ”/” 可有可無。