nginx模塊及location匹配規則


nginx模塊

ngx_http_charset_module(字符集)

# 語法格式
Syntax: charset charset | off;							# 語法提示
Default: charset off;								    # 默認字符集關閉
Context: http, server, location, if in location			  # 適用環境

# 1.操作演示
[root@web01 /yuming]# ll								# 默認站點目錄存在中文
total 16
-rw-r--r-- 1 root root  5 May 18 11:36 111111.txt
-rw-r--r-- 1 root root  4 May 18  2020 123.txt
-rw-r--r-- 1 root root 13 May 18  2020 index
-rw-r--r-- 1 root root  5 May 18 11:36 湯采玉.txt

# 1.1 瀏覽器顯示頁面存在亂碼(見圖一)

# 1.2 對此操作修改配置文件
[root@web01 /etc/nginx/conf.d]# vim yuming.conf 
server {
        listen 80;
        server_name www.tcy.com;
        charset utf-8,gbk;								# 添加此行信息即可
        root /yuming;
        index index.html;
   
}

# 1.3 瀏覽器顯示頁面正常 (見圖二)
  • 圖一

  • 圖二

autoindex_exact_size(文件大小顯示)

# autoindex常用參數
autoindex_exact_size off;
默認為on, 顯示出文件的確切大小,單位是bytes。
修改為off,顯示出文件的大概大小,單位是kB或者MB或者GB。

# 操作演示
1.修改配置文件
server {
        listen 80;
        server_name www.tcy.com;
        charset utf-8,gbk;

        location / {
        root /yuming;
        #index index.html;
        autoindex on;
        autoindex_exact_size off;						# 只需此項修改為off即可
        autoindex_localtime on;
        }

        location /download {
        alias /tmp/yyy;
        autoindex on;

        auth_basic           "renzheng";
        auth_basic_user_file /pass/download.pass;
        }
}

ngx_http_index_module(站點首頁)

# 語法格式
Syntax: index file ...;										# 語法使用提示
Default: index index.html;									# 默認樣式
Context: http, server, location								# 適用環境

# 操作演示
1.查看配置文件
server {
        listen 80;
        server_name www.tcy.com;
        charset utf-8,gbk;

        location / {
        root /yuming;									   
        index index.html;									# 修改站點首頁為/yuming下的index.html
     }
}

2.查看修改后的結果(見圖三)

  • 圖三

ngx_http_autoindex_module(自動首頁)

# 語法格式
Syntax: autoindex on | off;							# 語法使用提示
Default: autoindex off;								# 默認關閉自動首頁
Context: http, server, location						# 適用環境

# 操作演示
1. 修改配置文件
[root@web01 /etc/nginx/conf.d]# vim yuming.conf 
server {
        listen 80;
        server_name www.tcy.com;
        charset utf-8,gbk;

        location / {
        root /yuming;
        #index index.html;							# 注釋此行信息,不手動讀取站點寫index.html文件
        autoindex on;								# 自動讀取,站點目錄下內容以目錄形式顯示
        autoindex_exact_size off;
        autoindex_localtime on;

2.刪除站點目錄中index.html文件(如不進行刪除會自動讀取)
[root@web01 /yuming]# rm -rf index.html 

3. 檢測並且重啟nginx服務
[root@web01 /yuming]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 /yuming]# systemctl reload nginx

4. 查看頁面顯示結果(見圖四)

  • 圖四

autoindex_localtime (同步時間)

# autoindex_localtime ------- 自動同步服務器中的時間  注意:需要本地服務器開啟時間同步

# 語法格式
Syntax: autoindex_localtime on | off;					# 語法提示
Default: autoindex_localtime off;						# 默認關閉自動同步時間功能
Context: http, server, location							# 適用環境

# 操作演示
1. 修改配置文件
server {
        listen 80;
        server_name www.tcy.com;
        charset utf-8,gbk;

        location / {
        root /yuming;
        autoindex on;
        autoindex_localtime on;							# on為開啟時間同步功能
     
}
}

2. 對本地服務器進行時間同步
[root@web01 /etc/nginx/conf.d]# ntpdate time1.aliyun.com
18 May 15:42:54 ntpdate[7651]: adjust time server 203.107.6.88 offset 0.134676 sec

3. 在站點目錄創建文件
[root@web01 /yuming]# echo time > time.txt

4. 查看當前時間
[root@web01 /yuming]# date
Mon May 18 15:44:03 CST 2020

5. 瀏覽器查看效果(見圖五)
  • 圖五

ngx_http_stub_status_module(監控狀態)

# 語法格式
Syntax: stub_status;
Default: — 
Context: server, location

# 官方配置模板
location = /basic_status {
    stub_status;
}

# 操作演示
1.修改配置文件
[root@web01 /etc/nginx/conf.d]# vim yuming.conf 
server {
        listen 80;
        server_name www.tcy.com;
        charset utf-8,gbk;

        location / {
        root /yuming;
        #index index.html;
        autoindex on;
        #autoindex_exact_size off;
        autoindex_localtime on;
        }

        location = /tcy {								# 瀏覽器訪問多增加一個uri
           stub_status;									# 模塊信息
        }
}

2. 檢測配置文件並重啟
[root@web01 /etc/nginx/conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 /etc/nginx/conf.d]# systemctl reload nginx

3. 瀏覽器查看結果 (見圖六)

4. 瀏覽器顯示結果解釋
Active connections: 2 									# 活動連接數,兩個用戶連接
server accepts handled requests							 
# accepts 當前的總連接數TCP
# handled 成功的連接數TCP
# requests 總的http請求數
 11 11 8 	
  # 第一個11是總的客戶端請求TCP連接數	
  # 第二個11是服務端響應了客戶端連接,所以為成功連接TCP數量
  # 第三位8是TCP建立成功后,客戶端請求http的總數量
Reading: 0 Writing: 1 Waiting: 1 

Reading             # 請求
Writing             # 響應
Waiting             # 等待的請求數,開啟了keepalive

# 注意, 一次TCP的連接,可以發起多次http的請求, 如下參數可配置進行驗證,所以當長連接開啟,上面顯示的第一個11和第二個11都是不進行變化的,只有http請求數發生變化。
keepalive_timeout  0;   # 類似於關閉長連接
keepalive_timeout  65;  # 65s沒有活動則斷開連接
  • 圖六

ngx_http_auth_basic_module(用戶登錄認證)

· 基於用戶登陸認證 http_auth_basic_module

# 語法格式 
Syntax: auth_basic string | off;							# 語法提示操作
Default: auth_basic off;								    # 默認關閉登錄認證
Context: http, server, location, limit_except				  # 適用環境

# 官方格式
location / {
    auth_basic           "closed site";						# 提示信息,隨便定義
    auth_basic_user_file conf/htpasswd;						# 指定認證用戶密碼文件路徑
}

# 操作演示
1. 修改配置文件
server {
        listen 80;
        server_name www.tcy.com;
        charset utf-8,gbk;

        location / {
        root /yuming;
        #index index.html;
        autoindex on;
        #autoindex_exact_size off;
        autoindex_localtime on;
        }

        location /download {
        alias /tmp/yyy;
        autoindex on;

        auth_basic           "renzheng";						# 認證注釋,隨意
        auth_basic_user_file /pass/download.pass;			     # 指定認證文件路徑
        }
}

2. 密碼生成工具安裝(htpasswd)
[root@web01 /etc/nginx/conf.d]# yum install -y httpd-tools

# htpasswd使用方式(去掉-c選項,即可在第一個用戶之后添加第二個用戶,依此類推。)
-c:創建一個加密文件;
-n:不更新加密文件,只將加密后的用戶名密碼顯示在屏幕上;
-m:默認采用MD5算法對密碼進行加密;
-d:采用CRYPT算法對密碼進行加密;
-p:不對密碼進行進行加密,即明文密碼;
-s:采用SHA算法對密碼進行加密;
-b:在命令行中一並輸入用戶名和密碼而不是根據提示輸入密碼;
-D:刪除指定的用戶。

3. 生成用戶名和密碼到對應文件
[root@web01 /tmp/yyy]# mkdir /pass -p
[root@web01 /tmp/yyy]# htpasswd -b -c /pass/download.pass zls zls123   # 指定用戶為zls密碼zls123
Adding password for user zls



4. 檢測配置文件並重啟服務
[root@web01 /etc/nginx/conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 /etc/nginx/conf.d]# systemctl reload nginx

6. 瀏覽器訪問檢測(見圖七)

  • 圖七

  • 輸入用戶名密碼

ngx_http_access_module(訪問控制)

# ngx_http_access_module(針對ip進行限制訪問)

# 語法規則
Syntax: allow address | CIDR | unix: | all;						# 語法告知
Default: — 													 # 默認設置
Context: http, server, location, limit_except					# 適用環境

# 官網示例配置(一定要將拒絕所有寫最下方,規則匹配默認從上往下)
location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

# 操作演示
1. 修改配置文件(只允許10.0.0.0/24網段ip訪問)
[root@web01 /etc/nginx/conf.d]# vim ym.conf 
server {
    listen 80;
    server_name www.twg.com;
        location / {
                root /opt/;
                index index.html;
                deny 10.0.0.1;								# 拒絕此ip訪問
                allow 10.0.0.0/24;							# 允許此網段訪問
                deny all;									# 拒絕所有
        }
}

2. 檢查語法,重載配置文件
[root@web01 /etc/nginx/conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 /etc/nginx/conf.d]# systemctl reload nginx

3. 瀏覽器訪問結果顯示
ip:10.0.0.1 訪問(結果見圖八)
ip:10.0.0.7 訪問 (結果見圖九)
  • 圖八

  • 圖九

nginx的location優先級匹配

  • location語法優先級排序
匹配符 匹配規則 優先級
= 精確匹配 1
^~ 以某個字符串開頭 2
~ 區分大小寫的正則匹配 3
~* 不區分大小寫的正則匹配 4
!~ 區分大小寫不匹配的正則 5
!~* 不區分大小寫不匹配的正則 6
/ 通用匹配,任何請求都會匹配到 7
  • 網站配置優先級
# 1. 首先書寫配置文件(具備優先級最高=號)
[root@web01 /etc/nginx/conf.d]# vim xianzhi.conf 
server {
    listen 80;
    server_name www.aaa.com;
    location / {									# 優先級最低,所有請求都會進行匹配
        default_type text/html;
        return 200 "location /";
    }
 
    location =/ {									# 精確匹配 ,優先級最高,這訪問/權限最大
        default_type text/html;
        return 200 "location =/";
    }
 
    location ~ / {									# 區分大小的匹配,匹配/aaa路徑
        default_type text/html;
        return 200 "location ~/";
    }
 
 2. 查看測試結果 見圖11,后將location=精確匹配注釋后結果見圖12

 
 -------------------------------------常用location項------------------------------------------
# 通用匹配,任何請求都會匹配到
location / {
    ...
}
 
# 嚴格區分大小寫,匹配以.php結尾的都走這個location    (\.為轉義符)
location ~ \.php$ {
    ...
}
 
# 嚴格區分大小寫,匹配以.jsp結尾的都走這個location 
location ~ \.jsp$ {
    ...
}
 
# 不區分大小寫匹配,只要用戶訪問.jpg,gif,png,js,css 都走這條location(.*為任意字符匹配多次)
location ~* .*\.(jpg|gif|png|js|css)$ {
    ...
}
 
# 不區分大小寫匹配
location ~* "\.(sql|bak|tgz|tar.gz|.git)$" {
    ...
}


  • 最開始訪問結果(圖11)

  • 將配置文件中= 精確匹配注釋結果(圖12)

nginx訪問限制模塊

總結

# 針對連接頻率和連接限速哪個限制比較好
http協議的連接與請求,首先HTTP是建立在TCP基礎之上,在完成HTTP請求需要先建立TCP三次握手(稱為TCP連接),在連接的基礎上在完成HTTP的請求。

所以多個HTTP請求可以建立在一次TCP連接之上, 那么我們對請求的精度限制,當然比對一個連接的限制會更加的有效,因為同一時刻只允許一個TCP連接進入, 但是同一時刻多個HTTP請求可以通過一個TCP連接進入。所以針對HTTP的請求限制才是比較優的解決方案。

ngx_http_limit_conn_module

# ngx_http_limit_conn_module 連接頻率限制
· 可設置僅允許多少用戶進行連接,當超過此限制時,服務器將返回 錯誤 以回復請求

# 語法規則
Syntax:     limit_req_zone key zone=name:size rate=rate;	    # 語法 {http層定義}
Default: —													# 默認配置	
Context: http												# 使用環境
Syntax:	limit_conn zone number;								 # 語法 {server層調用}
Default:	-											   # 默認配置
Context:	http,server,location						   # 使用環境

# 官方示例
http {
    limit_conn_zone $ binary_remote_addr zone = addr:10m;

    ...

    服務器{

        ...

        位置/ download / {
            limit_conn地址1;
        }

# 操作演示
1. 在nginx主配置文件中添加內容(也可寫在子配置文件中,只要是處於http層即可)
[root@web01 /etc/nginx/conf.d]# cat ../nginx.conf 

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$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/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
	limit_conn_zone $remote_addr zone=aaa_zone:10m;				# 只需書寫此內容,定義單個連接數最大連接使用內存空間,這里定義10m,aaa_zone名為server調用名稱
}
------------------------------------------------------------------------------------------------
[root@web01 /etc/nginx/conf.d]# cat xianzhi.conf 
server {
	listen 80;
	server_name www.aaa.com;
	location / {
		root /aaa;
		index index.html;
	limit_conn aaa_zone 1;								# 調用http層定義名稱,只允許一個連接
	}
}


2. 演示結果(因環境所處為同一個網段,結果無法實現,需用公網測試方可)

ngx_http_limit_req_module

# ngx_http_limit_req_module 連接速率限制

# 語法規則
# http層
Syntax:	limit_req_zone key zone=name:size rate=rate [sync];		# 語法規則
Default:	—												# 默認使用
Context:	http											# 使用環境
# server層
Syntax:	limit_req zone=name [burst=number] [nodelay | delay=number];		# 語法規則
Default:	—														   # 默認使用
Context:	http, server, location										# 適用環境

# 官方實例
http {
    limit_req_zone $ binary_remote_addr zone = one:10m rate = 1r / s;

    ...

    服務器{

        ...

        位置/ search / {
            limit_req區域=一個突發= 5;
        }
        
# 操作演示
1. 主配置文件修改(也可在子配置文件的http層定義)
[root@web01 /etc/nginx/conf.d]# vim ../nginx.conf 

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$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/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    
 limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;	# 此配置文件定義只需添加此行信息,意為http標簽段定義請求限制, rate限制速率,限制單個ip一秒鍾最多一個請求
}
----------------------------------------------------------------------------------------
[root@web01 /aaa]# vim /etc/nginx/conf.d/xianzhi.conf 
server {
    listen 80;
    server_name www.aaa.com;
    location / {
        root /aaa;
        index index.html;
        limit_req zone=req_zone burst=3 nodelay;# 調用limit_req變量(http層),zone指定共享內存空間的名字(http),burst超過該配置的請求數,則返回503,nodelay延遲處理。
        limit_req_status 404;				# 自定義將默認505報錯改為404
        error_page 404 /333_error.html;		 # 將報錯頁面修改為404的同時,自定義錯誤頁面樣式
         }
}

3. 將自定義頁面圖片上傳圖床工具,並且保存html格式,放入到站點目錄下的錯誤頁面中
[root@web01 /aaa]# vim 333_error.html
<a href="https://sm.ms/image/aDF4ptNPz9AETLs" target="_blank"><img src="http
s://i.loli.net/2020/05/19/aDF4ptNPz9AETLs.jpg" /></a>

     
2. 檢測配置文件是否有誤,並且重載配置文件
[root@web01 /etc/nginx/conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 /etc/nginx/conf.d]# systemctl reload nginx

3. 查看實驗結果 (一秒內多次刷新結果,出現自定義404頁面)(見圖十)

  • 圖十(自定義圖片及自定義狀態碼)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM