Nginx Web服務(一)


一、Nginx原理介紹

  1.1:什么是Nginx

    Nginx是一個開源的,支持高性能、高並發的WWW服務和代理服務軟件

 

  1.2:Nginx的功能特點及應用場合

    ① 支持高並發:能支持幾萬並發連接,特別是針對靜態小文件業務

    ② 資源消耗少:在3萬並發連接的情況下,開始10個nginx的線程消耗不到200M

    ③ 可以做HTTP的反向代理及加速緩存,即負載均衡,內置對RS節點的服務器健康檢查

    ④ 具備squid等專業代理軟件的緩存功能

    ⑤ 支持異步網絡IO事件模型

 

  1.3:同步與異步的簡單介紹

    ① 同步:發送出去一直等待,直到被處理(效率低 安全性高)

    ② 異步:發送出去不管有沒有被處理,直接進行下一個請求(效率高 安全性低)

 

  1.4:epoll模型和select模型的區別

    Nginx所使用的模型就是異步epoll模型,所以他的效率高速度快,Apache使用的模型就是select模型

    PS:(在生產環境中大多數高並發的軟件都是使用的epoll的異步模型)

指標 select epoll
性能 隨着連接數的增加,性能是急劇下降的,處理成千上萬的連接數性能很差 隨着連接數的增加,性能基本上不會發生變化,處理成千上萬的連接數,性能很好
連接數 連接數有限制,處理的最大連接數不能超過1024,如要超過1024個連接數,需要修改FD_SETSIZE宏,並重新編譯 連接數沒有限制
內在處理機制 線性輪詢 回調callback
開發的復雜性

 

二、Nginx代理原理介紹

  2.1:正向/反向代理原理圖

  2.2:正向代理原理闡述

    正向代理:客戶端<-->代理-->服務端

    正向代理就是客戶端和服務器之間的中間服務器,為了從服務器取到內容,客戶端向代理服務器發送一個請求並指定目標服務器,然后代理服務器向服務器轉交請求並將獲得的內容回給客戶端,客戶端必須設置正向代理服務器,當然前提是你要知道正向代理服務器的IP地址和程序端口

    其實舉個例子就是

    A(客戶端)想租C(服務端)的房子,但是A(客戶端)並不認識C(服務端)租不到。
    B(代理)認識C(服務端)能租這個房子所以你找了B(代理)幫忙租到了這個房子。

    這個過程中C(服務端)不認識A(客戶端)只認識B(代理)
    C(服務端)並不知道A(客戶端)租了房子,只知道房子租給了B(代理)。

    這個樣做的目的是

    ① 訪問本無法訪問的服務器(Over the wall訪問谷歌,但是Over the wall的技術不僅僅是使用了傳統的正向代理技術還有其他的技術)

    ② 緩存(Cache)作用 

    ③ 客戶端訪問授權(可以限制指定的客戶端訪問)

    ④ 隱藏訪問者的行蹤(抓肉雞)

 

  2.3:反向代理原理闡述

    反向代理:客戶端-->代理<-->服務端

    反向代理正好與正向代理相反,對於客戶端而言代理服務器就是提供訪問業務的服務器,並且客戶端不需要進行任何的特別的設置,客戶端向反向代理的命名空間中的內容發送普通請求,接着反向代理將判斷向何處(提供訪問業務的服務器)轉發請求,並將獲得的內容返回給客戶端

    舉例說明

    A(客戶端)想租一個房子,B(代理)就把這個房子租給了他。
    這時候實際上C(服務端)才是房東。
    B(代理)是中介把這個房子租給了A(客戶端)。

 

    這個過程中A(客戶端)並不知道這個房子到底誰才是房東
    他都有可能認為這個房子就是B(代理)的

    使用反向代理的目的

    ① 保護和隱藏原始的資源服務器

    ② 實現服務器集群的負載均衡,實現客戶端高速訪問

PS:網上有人說NGINX不能做正向代理,其實是不對的。NGINX也可以做正向代理,不過用的人比較少了。

三、Nginx安裝

  3.1:編譯安裝

nginx的版本在不斷的更新中,以后我能可以去http://nginx.org/ 去下載最新的穩點版
yum -y install wget (可以使用rpm -qa wget 看看有沒有安裝,沒有安裝在執行yum安裝)
yum -y install pcre pcre-devel openssl openssl-devel (為了使用nginx的偽靜態功能,centos7 默認已經安裝了)
mkdir -p /server/software    (創建一個通用的存放軟件的目錄)
cd /server/software
wget -q http://nginx.org/download/nginx-1.12.2.tar.gz
tar xf nginx-1.12.2.tar.gz  -C /opt/
cd /opt/nginx-1.12.2
useradd nginxs -s /sbin/nologin -M
./configure --user=nginxs --group=nginxs --with-http_ssl_module --with-http_stub_status_module --prefix=/data/nginx-1.12.2/	# 配置

================================解釋=======================================
--user=nginxs 								# 指定安裝的用戶
--group=nginxs								# 指定安裝的組
--with-http_ssl_module						# 開啟https
--with-http_stub_status_module				# 開啟nginx的status監測
--prefix=/data/nginx-1.12.2/				# 指定安裝目錄
================================解釋=======================================

make && make install  # 編譯 安裝
ln -s /data/nginx-1.12.2/ /data/nginx	# 創建軟連接 為了工作中方便
/data/nginx/sbin/nginx 			# 啟動nginx
netstat -lntup | grep nginx 	# 檢查是否啟動成功


客戶端測試
curl -v 192.168.163.129(服務器地址)

  3.2:yum安裝

yum -y install pcre pcre-devel openssl openssl-devel (為了使用nginx的偽靜態功能,centos7 默認已經安裝了)
yum -y install epel-resease (centos的默認yum源沒有nginx的包,所以我們要在第三方yum源安裝)
yum -y install nginx
systemctl start nginx  # 啟動
netstat -lntup | grep nginx # 檢查是否啟動成功
客戶端測試 curl -v 192.168.163.129(服務器地址)

四、Nginx常用模塊

  4.1:常用模塊及功能介紹

    核心模塊官網地址:http://nginx.org/en/docs/ngx_core_module.html

    http模塊官網地址:http://nginx.org/en/docs/

    核心模塊:nginx的核心模塊負責nginx的全局應用,主要是對應主配置文件的Main區塊和Events區塊區域,這里有很多的Nginx的全局參數配置

    http標准模塊:這些標准模塊,雖然不是nginx軟件所必須的,但是都是很常用的

ngx_http_core_module			# 包括一些核心的http參數配置,對應http區塊部分
ngx_http_access_module			# 訪問控制模塊,用來控制網站用戶對nginx的訪問
ngx_http_gzip_module			# 壓縮模塊,對nginx的返回數據進行壓縮
ngx_http_fastcgi_module			# fastcgi模塊,和動態應用相關的模塊,如php
ngx_http_proxy_module			# proxy代理模塊
ngx_http_upstream_module		# 負載均衡模塊,可以實現網站的負載均衡及節點檢查
ngx_http_rewrite_module			# URL地址重寫模塊
ngx_http_limit_conn_module		# 限制用戶並發連接數及請求模塊
ngx_http_limit_req_module		# 根據定義的key限制nginx請求過程的速率
ngx_http_log_module			  # 訪問日志模塊,以指定的格式記錄訪問日志
ngx_http_auth_basic_module		# Web認證模塊,設置web用戶通過賬號密碼訪問nginx
ngx_http_ssl_module			  # ssl模塊 用於加密的http連接
ngx_http_stub_status_module		# 記錄nginx基本的訪問狀

五、Nginx配置文件說明

  5.1:nginx的配置文件(/etc/nginx.conf)基本解析說明

cat /etc/nginx/nginx.conf.default | egrep -v "#|^$"  # 對配置文件進行最小化


worker_processes  1;	# worker的進程數(和CPU的核心數一致最好)
events {				# 事件區塊的開始
    worker_connections  1024;	# 每個worker的最大連接數
}						# 事件區塊的結束
http {					# http區塊的開始	
    include       mime.types;	# 設定mime類型,類型由mime.type文件定義
    default_type  application/octet-stream; # 默認類型
    sendfile        on;	# 開啟高效的傳輸模式
    keepalive_timeout  65;	# 超時時間
    server {				# server區塊的開始
        listen       80;	# 監聽的端口
        server_name  localhost;	# 域名地址
        location / {		# 站點的根目錄
            root   html;	# 存放網站html文件的目錄
            index  index.html index.htm; # 打開網站的默認文件
        }
        error_page   500 502 503 504  /50x.html;	# 錯誤文件地址,出現錯誤訪問這個下面的html
        location = /50x.html {
            root   html;
        }
    }
}

六、Nginx兩種代理的配置

  6.1:正向代理

應用在nginx的server段,不要server_name,需要添加一個resolver。
cat /etc/nginx/nginx.conf

worker_processes  1;
error_log /var/log/nginx/error.log;   # 配置錯誤日志默認級別error
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
	server {
	    # 配置DNS解析IP地址,比如 Google Public DNS,以及超時時間(5秒)
	    resolver 8.8.8.8;    # 必需
	    resolver_timeout 5s;

	    # 監聽端口
	    listen 8080;

	    access_log  /home/reistlin/logs/proxy.access.log;
	    error_log   /home/reistlin/logs/proxy.error.log;

	    location / {
	        # 配置正向代理參數
	        proxy_pass $scheme://$host$request_uri;
	        # 解決如果URL中帶"."后Nginx 503錯誤
	        proxy_set_header Host $http_host;

	        # 配置緩存大小
	        proxy_buffers 256 4k;
	        # 關閉磁盤緩存讀寫減少I/O
	        proxy_max_temp_file_size 0;
	         # 代理連接超時時間
	        proxy_connect_timeout 30;

	        # 配置代理服務器HTTP狀態緩存時間
	        proxy_cache_valid 200 302 10m;
	        proxy_cache_valid 301 1h;
	        proxy_cache_valid any 1m;
	    }
	}
}
client端:
一次代理,直接在shell執行:
#export http_proxy=http://192.168.163.132:8080

永久使用:
#vim .bashrc
export http_proxy=http://192.168.163.132:8080
#source  .bashrc

  6.2:反向代理

反向代理的配置
cat /etc/nginx/nginx.conf

worker_processes  2; #啟動進程,通常設置成和cpu的數量相等
events {
    worker_connections  1024; #單個后台worker process進程的最大並發鏈接數
}
http {
    include       mime.types; #設定mime類型,類型由mime.type文件定義
    default_type  application/octet-stream;
    #sendfile 指令指定 nginx 是否調用 sendfile 函數(zero copy)來輸出文件,對於普通應用,
    #必須設為 on,如果用來進行下載等應用磁盤IO重負載應用,可設置為 off,以平衡磁盤與網絡I/O處理速度,降低系統的uptime.
    sendfile on;
    keepalive_timeout  65; #連接超時時間
    server {
        listen 80; #偵聽80端口
        server_name localhost; # 定義使用www.xx.com訪問
        charset utf-8;
        location / {
            root   html;
            add_header Cache-Control no-store;
            add_header 'Access-Control-Allow-Origin' '*';
            index  index.html index.htm;
        }
        location /request/ {
            root /request;		# 網站的資源路徑
            #請求替換地址 例如要請求http://localhost:8888/login/ 也就是請求http://localhost/request/
            proxy_pass http://localhost:8888/login/; 	
            proxy_redirect             off; 
            proxy_set_header           Host $host; #請求主機頭字段,否則為服務器名稱。
            # 后端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
        	proxy_set_header           X-Real-IP $remote_addr; 
        	proxy_set_header           X-Forwarded-For $proxy_add_x_forwarded_for; 

            client_max_body_size       10m; #允許客戶端請求的最大單文件字節數
        	client_body_buffer_size    128k; #緩沖區代理緩沖用戶端請求的最大字節數
        	proxy_connect_timeout      300; #nginx跟后端服務器連接超時時間(代理連接超時)
        	proxy_send_timeout         300; #后端服務器數據回傳時間(代理發送超時)
        	proxy_read_timeout         300; #連接成功后,后端服務器響應時間(代理接收超時)
        	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服務器傳
            proxy_headers_hash_max_size 1024; #存放http報文頭的哈希表容量上限,默認為512個字符
            proxy_headers_hash_bucket_size 128; #設置頭部哈希表大小 默認為64
            
        }
        location ~ ^/html5/ {
            rewrite  /html5(.*)$ $1 break; #該指令根據表達式來重定向URI, 路徑中存在/html5/的
            expires -1; #緩存
            root D:\html5; #前端靜態文件物理路徑 通過http://localhost/html5/來訪問D盤html5下的文件夾
        }
    }
}

七、Nginx虛擬主機配置

  6.1:什么是虛擬主機

    在web服務里面就是一個獨立的網站站點,這個站點對應獨立的域名,具有獨立的程序及資源目錄,可以獨立的對外提供服務

  6.2:虛擬主機的類型

    ① 基於域名的虛擬主機

      相同的IP端口不同的域名提供不同的資源,最常用的

    ② 基於端口的虛擬主機

      相同的IP不同的端口提供不同的資源(局域網最常用的)

    ③ 基於IP的虛擬主機

      相同端口不同的IP提供不同的資源(最不常用,一般也不會用到)

  6.3:虛擬主機的配置(在nginx.conf配置文件中添加server區塊)

    ① 基於域名的虛擬主機

vim /etc/nginx/nginx.conf

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  www.zhujingzhi.org;     # 域名不一樣
        location / {
            root   html/www;				 # 記得添加網站的資源目錄	
            index  index.html index.htm;
        }
    }
     server {
        listen       80;
        server_name  bbs.zhujingzhi.org;	# 域名不一樣
        location / {	
            root   html/bbs;				# 記得添加網站的資源目錄
            index  index.html index.htm;
        }
    }
     server {
        listen       80;
        server_name  blos.zhujingzhi.org;	# 域名不一樣
        location / {
            root   html/blos;				# 記得添加網站的資源目錄
            index  index.html index.htm;
        }
    }
}  

    ② 基於端口的虛擬主機

vim /etc/nginx/nginx.conf

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;					# 端口也不一樣	
        server_name  www.zhujingzhi.org;    # 域名不一樣
        location / {
            root   html/www;				# 記得添加網站的資源目錄	
            index  index.html index.htm;
        }
    }
     server {
        listen       81;					# 端口也不一樣
        server_name  bbs.zhujingzhi.org;	# 域名不一樣
        location / {	
            root   html/bbs;				# 記得添加網站的資源目錄
            index  index.html index.htm;
        }
    }
     server {
        listen       82;					# 端口也不一樣
        server_name  blos.zhujingzhi.org;	# 域名不一樣
        location / {
            root   html/blos;				# 記得添加網站的資源目錄
            index  index.html index.htm;
        }
    }
}

    ③ 基於IP的虛擬主機

vim /etc/nginx/nginx.conf

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       192.168.163.129:80;	# 端口一樣IP不一樣	
        server_name  www.zhujingzhi.org;    # 域名不一樣
        location / {
            root   html/www;				# 記得添加網站的資源目錄	
            index  index.html index.htm;
        }
    }
     server {
        listen       192.168.163.130:80;	# 端口一樣IP不一樣
        server_name  bbs.zhujingzhi.org;	# 域名不一樣
        location / {	
            root   html/bbs;				# 記得添加網站的資源目錄
            index  index.html index.htm;
        }
    }
     server {
        listen       192.168.163.131:80;	# 端口一樣IP不一樣
        server_name  blos.zhujingzhi.org;	# 域名不一樣
        location / {
            root   html/blos;				# 記得添加網站的資源目錄
            index  index.html index.htm;
        }
    }
}

PS:修改完配置文件(因為nginx支持reload方法)所以我們要重新的平滑重啟下 在重啟之前一定nginx -t 檢查下語法,在配置基於IP的虛擬主機的時候IP一定是存在的,不然會出現語法錯誤

八、Nginx狀態模塊使用

  7.1:nginx status 狀態模塊配置(--with-http_stub_status_module參數)

# 在編譯安裝的時候指定--with-http_stub_status_module參數就是開啟了狀態監測模塊


# 主配置文件
cat /etc/nginx/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;	# 我們把server區塊分離出來了放到了/etc/nginx/conf.d/下,然后用include導入
}



# 狀態監測配置文件(這個就是要配置的狀態監測的server區塊寫到.conf里面在主配置文件中導入)
cat  >> /etc/nginx/conf.d/status.conf <<EOF
> # status
> server {
>         listen    80;
>         server_name    status.zhujingzhi.org;
>         location / {
>                 stub_status on;        # 開啟狀態監測
>                 access_log  off;		 # 拒絕寫日志
>				  allow 192.168.163.0/24;  # 允許訪問的地址
>				  deny all;				 # 決絕訪問	
>         }
>     }
> EOF

  7.2:輸出結果詳細解析

沒有域名解析,我們要添加hosts文件(只針對測試環境)
vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.163.132 status.zhujingzhi.org    # 我們添加的


curl status.zhujingzhi.org  # 訪問狀態監測的地址

# 得到的結果
Active connections: 1
server accepts handled requests
 27 27 27
Reading: 0 Writing: 1 Waiting: 0

# 結果的解釋
Active connections: 表示Nginx正處理的活動連接數
server:表示Nginx啟動到現在共處理了多少個連接
accepts:表示Nginx啟動到現在共處理成功創建的握手次數
handled requests:表示共處理了多少次請求
Reading:表示讀取到客戶端的Header信息數
Writing:表示返回給客戶端的Header信息數
Waiting:表示已經處理完正在等候下一次請求指令的駐留連接數,在開啟keeplive的情況下,這個值等於active-(reading+writing)

 PS:為了安全起見,這個狀態信息要防止外部用戶查看

  7.3:利用監控系統監控nginx的狀態(擴展)

九、Nginx日志詳情

  8.3:訪問日志內容解析(access.log)

訪問日志
參數
log_format:用來定義日志的格式
access_log:用來注定日志文件的路徑及使用的何種日志格式記錄日志

# 默認的日志格式(放在http標簽內)
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

# 日志格式參數說明
$remote_addr	# 記錄客戶端訪問網站的地址
$remote_user	# 遠程客戶端用戶的名稱
$time_local		# 記錄訪問時間與時區
$request		# 用戶的http請求起始行信息
$status			# http狀態碼,記錄請求返回的狀態
$body_bytes_sent	# 服務器發送給客戶端的響應body字節數
$http_referer	# 記錄此次請求是從哪個鏈接訪問過來的可以根據refer進行防盜鏈的設置
$http_user_agent 	# 記錄客戶端的訪問信息,例如:瀏覽器,手機客戶端等
$http_x_forwarded_for	# 當前端有代理服務器時,設置Web節點記錄客戶端地址的配置,此參數生效的前提是代理服務器上也要進行配置x_forwarded_for設置

訪問日志配置文件設置
在server區塊中添加access_log /etc/log/access.log main; 這里的main表示的是在http標簽中設置的日志格式的main 這個可以是main1、main2 等不同的格式記錄日志

  8.4:錯誤日志內容解析(error.log)

錯誤日志
屬於核心功能模塊ngx_core_module參數,該參數的名字為error_log,可以放在main區塊中全局配置,也可以放在不同的虛擬主機中單獨記錄虛擬主機的錯誤信息

語法
error_log file level;
error_log	# 固定的參數
file		# 日志的文件
level		# 日志的級別

日志的級別包含:debug|info|notice|warn|error|crit|alert|emerg ,級別越高記錄的信息越少,生產中一般使用warn|error|crit 這個三個級別
PS:千萬不要使用info 會產生大量的I/O

  8.1:配置文件配置日志

  訪問日志配置

cat /etc/nginx/nginx.conf

worker_processes  1;
error_log /var/log/nginx/error.log;   # 配置錯誤日志默認級別error
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    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;						# 啟動訪問日志
    server {
        listen       80;
        server_name  www.zhujingzhi.org;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

  錯誤日志配置

cat /etc/nginx/nginx.conf

worker_processes  1;
error_log /var/log/nginx/error.log;   # 配置錯誤日志默認級別error
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  www.zhujingzhi.org;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

十、Nginx日志切割

  9.1:日志切割的方式

  9.2:日志切割腳本+crontab計划任務

  9.3:常用的日志收集工具(rsyslog、awstats、flume、ELK、storm)

十一、Nginx認證訪問

  10.1:為什么要配置認證訪問

    有些時候我們用nginx要做內部的網站訪問,或者是用nginx來做文件服務器給內部人員使用,為了安全我們就要用到認證機制,保證數據的安全

  10.2:配置日志訪問的方法

cat  /etc/nginx/nginx.conf

worker_processes  1;
error_log /var/log/nginx/error.log;   # 配置錯誤日志默認級別error
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
	server {
		listen 80; #監聽端口為80
		server_name www.zhujingzhi.com; #虛擬主機網址
		location / {
		root html/bbs; # 虛擬主機網站根目錄
		index index.html index.htm; # 虛擬主機首頁
		auth_basic "secret"; # 虛擬主機認證命名
		auth_basic_user_file /usr/local/nginx/passwd.db; # 虛擬主機用戶名密碼認證數據庫
	}
		location /status {
		stub_status on; # 開啟網站監控狀態
		access_log /usr/local/nginx/logs/www1_status.log; # 監控日志
		auth_basic "NginxStatus"; 
		}
	}
}



我們還要生成用戶名密碼文件
通過htpasswd命令生成用戶名及對應密碼數據庫文件
htpasswd -c /usr/local/nginx/passwd.db nginxtest

十二、Nginx Location

  location指令的作用是可以根據用戶請求的URI來執行不同的應用,其實就是根據用戶的請求的網站的地址URL匹配,匹配成功即進行相關的操作(相當於if...else語句,女孩子你有錢我就嫁給你 O(∩_∩)O哈哈~)

  ① location語法

location[=|~|~*|^~]uri{
	.....
}

location   	# 指令
[=|~|~*|^~|!~|!~|@]	# 匹配標識
uri			# 匹配的網站地址
{...}		# 匹配URI后要執行的配置段
	
====================================================================================

匹配標識解釋
=		# 精確匹配
~		# 開頭表示區分大小寫的正則匹配
~*		# 開頭表示不區分大小寫的正則匹配
^~		# 常規的字符串匹配檢查之后,不做正則表達式的檢查
!~和!~* # 分別為區分大小寫不匹配及不區分大小寫不匹配 的正則
/ 		# 通用匹配,任何請求都會匹配到。
@		# "@" 定義一個命名的 location,使用在內部定向時,例如 error_page, try_files


location  = / {
  # 只匹配"/".
  [ configuration A ] 
}
location  / {
  # 匹配任何請求,因為所有請求都是以"/"開始
  # 但是更長字符匹配或者正則表達式匹配會優先匹配
  [ configuration B ] 
}
location  /documents/ {
  # 匹配以documents開頭的地址
  [ configuration C ] 
}
location ^~ /images/ {
  # 匹配任何以 /images/ 開始的請求,並停止匹配 其它location
  [ configuration D ] 
}
location ~* .(gif|jpg|jpeg)$ {
  # 匹配以 gif, jpg, or jpeg結尾的請求. 
  # 但是所有 /images/ 目錄的請求將由 [Configuration C]處理.   
  [ configuration E ] 
}

  ② 配置location

主配置文件
cat /etc/nginx/nginx.conf

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;    # 導入虛擬主機文件
}


# 虛擬主機文件配置location
cat /etc/nginx/conf.d/www.conf

# www
server {
        listen       80;
        server_name  www.zhujingzhi.org;
        location / {
            return 401;
            #root   html/www;
            #index  index.html index.htm;
        }
        location = /{
            return 402;
        }
        location /documents/ {
            return 403;
        }
        location ^~ /images/ {
            return 404;
        }
        location ~* .(gif|jpg|jpeg)$ {
            return 405;
        }
    }


客戶端測試
為了測試我們要加hosts文件
cat /etc/hosts

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4 
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.163.132 status.zhujingzhi.org www.zhujingzhi.org

使用curl 測試 返回我們配置在location中的return返回值
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.zhujingzhi.org
402
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.zhujingzhi.org/
402
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.zhujingzhi.org/index.html
401
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.zhujingzhi.org/documents/document.html
403
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.zhujingzhi.org/images/1.png
404
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.zhujingzhi.org/documents/2.jpg
405

  ③ 結論

用戶請求的URI				完整的URL						   匹配的返回值
/					http://www.zhujingzhi.org/					402	
/index.html                     http://www.zhujingzhi.org/index.html    	          401
/documents/document.html   	      http://www.zhujingzhi.org/documents/document.html          403
/images/1.png                   http://www.zhujingzhi.org/images/1.png	               404
/documents/2.jpg                http://www.zhujingzhi.org/documents/2.jpg               405


location 優先級
	1、Directives with the = prefix that match the query exactly. If found, searching stops.
	2、All remaining directives with conventional strings, longest match first. If this match used the ^~ prefix, searching stops.
	3、Regular expressions, in order of definition in the configuration file.
	4、If #3 yielded a match, that result is used. Else the match from #2 is used.

	1、=前綴的指令嚴格匹配這個查詢。如果找到,停止搜索。
	2、所有剩下的常規字符串,最長的匹配。如果這個匹配使用^〜前綴,搜索停止。
	3、正則表達式,在配置文件中定義的順序。
	4、如果第3條規則產生匹配的話,結果被使用。否則,使用第2條規則的結果。

十三、Nginx rewrite

 


免責聲明!

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



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