Nginx Web服務(一)

1、Nginx原理介紹

  1.1:什麼是Nginxphp

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

 

  1.2:Nginx的功能特色及應用場合前端

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

    ② 資源消耗少:在3萬併發鏈接的狀況下,開始10個nginx的線程消耗不到200Mnginx

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

    ④ 具有squid等專業代理軟件的緩存功能正則表達式

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

 

  1.3:同步與異步的簡單介紹數據庫

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

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

 

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

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

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

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

 

2、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也能夠作正向代理,不過用的人比較少了。

3、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(服務器地址)

4、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基本的訪問狀

5、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;
        }
    }
}

6、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下的文件夾
        }
    }
}

7、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必定是存在的,否則會出現語法錯誤

8、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的狀態(擴展)

9、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 這個能夠是main一、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;
        }
    }
}

10、Nginx日誌切割

  9.1:日誌切割的方式

  9.2:日誌切割腳本+crontab計劃任務

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

11、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

12、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 優先級
	一、Directives with the = prefix that match the query exactly. If found, searching stops.
	二、All remaining directives with conventional strings, longest match first. If this match used the ^~ prefix, searching stops.
	三、Regular expressions, in order of definition in the configuration file.
	四、If #3 yielded a match, that result is used. Else the match from #2 is used.

	一、=前綴的指令嚴格匹配這個查詢。若是找到,中止搜索。
	二、全部剩下的常規字符串,最長的匹配。若是這個匹配使用^〜前綴,搜索中止。
	三、正則表達式,在配置文件中定義的順序。
	四、若是第3條規則產生匹配的話,結果被使用。不然,使用第2條規則的結果。

十3、Nginx rewrite

相關文章
相關標籤/搜索