3.12 nginx安裝及使用

1. nginx升級、添加模塊

//查看當前版本
[root@130 nginx-1.16.1]# nginx -V					
nginx version: nginx/1.12.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log

//備份當前版本
[root@130 nginx-1.16.1]# cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx-1.12
[root@130 nginx-1.16.1]# ls /usr/local/nginx/sbin/
nginx  nginx-1.12

//升級版本
[root@130 ~]# cd nginx-1.16.1
[root@130 nginx-1.16.1]# ls ..
anaconda-ks.cfg  nginx-1.16.1.tar.gz            nginx-http-echo-module-master.zip
nginx-1.16.1     nginx-http-echo-module-master  pass
[root@130 nginx-1.16.1]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@130 nginx-1.16.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../nginx-http-echo-module-master
[root@130 nginx-1.16.1]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
[root@130 nginx-1.16.1]# make

//停止現有nginx服務
[root@130 nginx-1.16.1]# nginx -s stop
[root@130 nginx-1.16.1]# ss -anlt
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128             *:22                          *:*                  
LISTEN      0      128     127.0.0.1:9000                        *:*                  
LISTEN      0      128            :::22                         :::*                  
LISTEN      0      80             :::3306                       :::*

//升級nginx
[root@130 nginx-1.16.1]# ls objs/
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src
[root@130 nginx-1.16.1]# cp objs/nginx /usr/local/nginx/sbin/.
cp:是否覆蓋"/usr/local/nginx/sbin/./nginx"? y
[root@130 nginx-1.16.1]# nginx
[root@130 nginx-1.16.1]# nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../nginx-http-echo-module-master

2. nginx日誌log定義格式

log_format 定義日誌格式

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  logs/access.log  main;

//注意:此處可用變量爲nginx各模塊內建變量

3.location使用

location區段,通過指定模式來與客戶端請求的URI相匹配

//功能:允許根據用戶請求的URI來匹配定義的各location,匹配到時,此請求將被相應的location配置塊中的配置所處理,例如做訪問控制等功能

//語法:location [ 修飾符 ] pattern {......}

常用修飾符說明:

修飾符 功能
= 精確匹配
~ 正則表達式模式匹配,區分大小寫
~* 正則表達式模式匹配,不區分大小寫
^~ 前綴匹配,類似於無修飾符的行爲,也是以指定模塊開始,不同的是,如果模式匹配,那麼就停止搜索其他模式了,不支持正則表達式
@ 定義命名location區段,這些區段客戶端不能訪問,只可以由內部產生的請求來訪問,如try_files或error_page等

3.1 無修飾符

沒有修飾符表示必須以指定模式開始,如:

server {
  server_name www.idfsoft.com;
  location /abc {
    ......
  }
}

那麼如下內容就可正確匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
  • http://www.idfsoft.com/abc/
    示例:
[root@130 conf]# vim nginx.conf
    	location /abc {
            root html;
            echo 'haha\n';
        }
[root@130 conf]# nginx -s reload
[root@130 conf]# curl http://192.168.80.130/abc
haha
[root@130 conf]# curl http://192.168.80.130/abc?a=1\&b=2
haha
[root@130 conf]# curl http://192.168.80.130/abc/
haha

3.2 = 使用方法

=:表示必須與指定的模式精確匹配,如:

server {
  server_name www.idfsoft.com;
  location = /abc {
    ......
  }
}

那麼如下內容就可正確匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
    如下內容則無法匹配:
  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/abc/abcde
    示例:
[root@130 conf]# vim nginx.conf
    	location = /abc {
            root html;
            echo 'haha\n';
        }
[root@130 conf]# nginx -s reload
[root@130 conf]# curl http://192.168.80.130/abc
haha
[root@130 conf]# curl http://192.168.80.130/abc?a=1\&b=2
haha
[root@130 conf]# curl http://192.168.80.130/abc/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

3.3 ~ (指定正則表達式區分大小寫匹配)

~:表示指定的正則表達式要區分大小寫,如:

server {
  server_name www.idfsoft.com;
  location ~ ^/abc$ {
  ......
  }
}

那麼如下內容就可正確匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
    如下內容則無法匹配:
  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/ABC
  • http://www.idfsoft.com/abcde
  • 示例:
[root@130 conf]# vim nginx.conf
    	location ~ ^/abc$ {
            root html;
            echo 'haha\n';
        }
[root@130 conf]# nginx -s reload
[root@130 conf]# curl http://192.168.80.130/abc
haha
[root@130 conf]# curl http://192.168.80.130/abc/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>
[root@130 conf]# curl http://192.168.80.130/ABC
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

3.4 ~* (指定的正則表達式不區分大小寫匹配)

~*:表示指定的正則表達式不區分大小寫,如:

server {
  server_name www.idfsoft.com;
  location ~* ^/abc$ {
    ......
  }
}

那麼如下內容就可正確匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
  • http://www.idfsoft.com/ABC
    如下內容則無法匹配:
  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/abcde

示例:

[root@130 conf]# vim nginx.conf
    	location ~ ^/abc$ {
            root html;
            echo 'haha\n';
        }
[root@130 conf]# nginx -s reload
[root@130 conf]# curl http://192.168.80.130/abc
haha
[root@130 conf]# curl http://192.168.80.130/ABC
haha
[root@130 conf]# curl http://192.168.80.130/abc/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

~:類似於無修飾符的行爲,也是以指定模式開始,不同的是,如果模式匹配,則停止搜索其他模式

3.5 location查找順序和優先級

查找順序和優先級:由高到底依次爲

  1. 帶有=的精確匹配優先
  2. 正則表達式按照他們在配置文件中定義的順序
  3. 帶有^~修飾符的,開頭匹配
  4. 帶有*修飾符的,如果正則表達式與URI匹配
  5. 沒有修飾符的精確匹配

優先級次序如下:

( location = 路徑 ) --> ( location ^~ 路徑 ) --> ( location ~ 正則 ) --> ( location ~* 正則 ) --> ( location 路徑 )

4. 訪問控制

用於location段
allow:設定允許哪臺或哪些主機訪問,多個參數需另起一行,以“;”結束
deny:設定禁止哪臺或哪些主機訪問,多個參數需另起一行,以“;”結束
示例:

location  / {
      root   html/zabbix;
      index  index.php index.html;
      allow 192.168.80.0/24;
      allow 192.168.80.1/32;
      deny all;
}

5. 基於用戶認證

auth_basic "歡迎信息";
auth_basic_user_file "/path/to/user_auth_file"

user_auth_file內容格式爲:

username:password

這裏的密碼爲加密後的密碼串,建議用htpasswd來創建此文件:

htpasswd -c -m /path/to/.user_auth_file USERNAME

示例:

[root@130 ~]# htpasswd -c -m /usr/local/nginx/conf/userfile/.user_auth_file yusy
New password: 
Re-type new password: 
Adding password for user yusy
[root@130 ~]# vim /usr/local/nginx/conf/nginx.conf
      location  / {
            root   html/zabbix;
            index  index.php index.html;

            auth_basic "welcome to zabbix";
            auth_basic_user_file "/usr/local/nginx/conf/userfile/.user_auth_file";
      }
[root@130 ~]# nginx -s reload

效果:
在這裏插入圖片描述

6. 開啓狀態界面

開啓status:

location /status {
  stub_status {on | off};
  allow 192.168.80.1/32;
  deny all;
}

訪問狀態頁面的方式:http://server_ip/status

狀態頁面信息詳解:

狀態碼 表示的意義
Active connections 2 當前所有處於打開狀態的連接數
accepts 總共處理了多少個連接
handled 成功創建多少握手
requests 總共處理了多少個請求
Reading nginx讀取到客戶端的Header信息數,表示正處於接收請求狀態的連接數
Writing nginx返回給客戶端的Header信息數,表示請求已經接收完成,且正處於處理請求或發送響應的過程中的連接數
Waiting 開啓keep-alive的情況下,這個值等於active - (reading +writing),意思就是Nginx已處理完正在等候下一次請求指令的駐留連接

7. zabbix監控網站

寫腳本監控nginx狀態

[root@130 scripts]# cat nginx-accept.sh 
#/bin/bash
status=$(curl http://192.168.80.130/status 2>/dev/null |awk 'NR==3{print $1}')
echo $status
[root@130 scripts]# cat nginx-request.sh 
#/bin/bash
status=$(curl http://192.168.80.130/status 2>/dev/null |awk 'NR==3{print $3}')
echo $status

[root@130 scripts]# vim /usr/local/etc/zabbix_agentd.conf
UnsafeUserParameters=1

UserParameter=nginx-accept,/bin/bash /scripts/nginx-accept.sh
UserParameter=nginx-request,/bin/bash /scripts/nginx-request.sh

zabbix添加監控項
1.點擊監控項
在這裏插入圖片描述
2.添加監控項
在這裏插入圖片描述
3.添加監控事件
在這裏插入圖片描述
在這裏插入圖片描述
查看監控事件
在這裏插入圖片描述
在這裏插入圖片描述

8. rewrite

語法:rewrite regex replacement flag;,如:

rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;

此處的$1用於引用(.*.jpg)匹配到的內容,又如:

rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

示例:
1. 初始路徑

[root@130 nginx]# ls html/images/
1.jpg
[root@130 nginx]# vim conf/nginx.conf
	location  /images {
        root html;
    }

在這裏插入圖片描述
修改路徑後,爲保證原路徑依然可用使用rewrite重寫訪問到原網站或原路徑

[root@130 nginx]# vim conf/nginx.conf
	    location  /images {
            root html;
        }
        location /imgs {
            rewrite ^/imgs/(.*)$ /images/$1 break;
        }
[root@130 nginx]# nginx -s reload

在這裏插入圖片描述
跳轉到其它URL

[root@130 nginx]# vim conf/nginx.conf
	location /imgs {
            rewrite ^/imgs/(.*)$ http://www.baidu.com break;
        }
[root@130 nginx]# nginx -s reload        

在這裏插入圖片描述
在這裏插入圖片描述
如上例所示,replacement可以是某個路徑,也可以是某個URL

常見的flag

flag 作用
last 基本上都用這個flag,表示當前的匹配結束,繼續下一個匹配,最多匹配10個到20個,一旦此rewrite規則重寫完成後,就不再被後面其它rewrite規則進行處理,而是由UserAgent重新對重寫後的URL再一次發起請求,並從頭開始執行類似的過程
break 中止Rewrite,不再繼續匹配,一旦此rewrite規則重寫完成後,由UserAgent對新的URL重新發起請求,且不再會被當前location內的任何rewrite規則所檢查
redirect 以臨時重定向的HTTP狀態302返回新的URL
permanent 以永久重定向的HTTP狀態301返回新的URL

rewrite模塊的作用是用來執行URL重定向。這個機制有利於去掉惡意訪問的url,也有利於搜索引擎優化(SEO)

nginx使用的語法源於Perl兼容正則表達式(PCRE)庫,基本語法如下:

標識符 意義
^ 必須以^後的實體開頭
$ 必須以$前的實體結尾
. 匹配任意字符
[] 匹配指定字符集內的任意字符
[^] 匹配任何不包括在指定字符集內的任意字符串
| 匹配| 之前或之後的實體
() 分組,組成一組用於匹配的實體,通常會有 | 來協助

捕獲子表達式,可以捕獲放在()之間的任何文本,比如:

^(hello|sir)$       //字符串爲“hi sir”捕獲的結果:$1=hi$2=sir

//這些被捕獲的數據,在後面就可以當變量一樣使用了

9. if

語法:if (condition) {…}
應用場景:

  • server段
  • location段

常見的condition

  • 變量名(變量值爲空串,或者以“0”開始,則爲false,其它的均爲true)
  • 以變量爲操作數構成的比較表達式(可使用=,!=類似的比較操作符進行測試)
  • 正則表達式的模式匹配操作
    • ~:區分大小寫的模式匹配檢查
    • ~*:不區分大小寫的模式匹配檢查
    • !和!*:對上面兩種測試取反
  • 測試指定路徑爲文件的可能性(-f,!-f)
  • 測試指定路徑爲目錄的可能性(-d,!-d)
  • 測試文件的存在性(-e,!-e)
  • 檢查文件是否有執行權限(-x,!-x)

10. 基於瀏覽器實現分離案例

if ($http_user_agent ~ Firefox) {
  rewrite ^(.*)$ /firefox/$1 break;
}

if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;
}

if ($http_user_agent ~ Chrome) {
  rewrite ^(.*)$ /chrome/$1 break;
}

11. 防盜鏈案例

location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.idfsoft.com/403.html;
  }
}

12. 反向代理和負載均衡

nginx 通常被用作後端服務器的反向代理,這樣就可以很方便的實現動靜分離以及負載均衡,從而大大提高服務器的處理能力。

nginx實現動靜分離,其實就是在反向代理的時候,如果是靜態資源,就直接從nginx發佈的路徑去讀取,而不需要從後臺服務器獲取了。

  • 但是要注意,這種情況下需要保證後端跟前端的程序保持一致,可以使用Rsync做服務端自動同步或者使用NFS、MFS分佈式共享存儲。

Http Proxy模塊,功能很多,最常用的是proxy_passproxy_cache

  • 如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模塊,用來清除指定的URL緩存。這個集成需要在安裝nginx的時候去做,如:
./configure --add-module=../ngx_cache_purge-1.0 ......

nginx通過upstream模塊來實現簡單的負載均衡,upstream需要定義在http段內

  • 在upstream段內,定義一個服務器列表,默認的方式是輪詢,如果要確定同一個訪問者發出的請求總是由同一個後端服務器來處理,可以設置ip_hash,如:
upstream idfsoft.com {
  ip_hash;			//利用hash算法使客戶端在一段時間內固定訪問一臺web服務器
  server 127.0.0.1:9080 weight=5;	//weight指定該web服務器允許被一個客戶端訪問次數,達到次數則替換爲訪問下一臺web服務器
  server 127.0.0.1:8080 weight=5;
  server 127.0.0.1:1111;
}
  • 注意:這個方法本質還是輪詢,而且由於客戶端的ip可能是不斷變化的,比如動態ip,代理,翻牆等,因此ip_hash並不能完全保證同一個客戶端總是由同一個服務器來處理。

定義好upstream後,需要在server段內添加如下內容:

server {
  location / {
    proxy_pass http://idfsoft.com;
  }
}

示例:

//web服務器防火牆均需要關閉
systemctl disable firewalld
systemctl stop firewalld
setenforce 0

//配置web服務器128
[root@128 ~]# yum -y install httpd
[root@128 ~]# vim /etc/httpd/conf/httpd.conf
ServerName www.example.com:80
[root@128 html]# echo 'this 128: hello'>/var/www/html/index.html
[root@128 html]# systemctl restart httpd
[root@128 html]# ss -anlt
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128             *:111                         *:*                  
LISTEN      0      128             *:22                          *:*                  
LISTEN      0      100     127.0.0.1:25                          *:*                                  
LISTEN      0      128            :::80                         :::*      

//配置web服務器131
[root@131 ~]# yum -y install httpd
[root@131 ~]# vim /etc/httpd/conf/httpd.conf
ServerName www.example.com:80
[root@131 ~]# echo 'this 131: hello'>/var/www/html/index.html
[root@131 ~]# systemctl restart httpd
[root@131 ~]# ss -anlt
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128             *:22                          *:*                  
LISTEN      0      50              *:3306                        *:*                  
LISTEN      0      128            :::80                         :::*                  
LISTEN      0      128            :::22                         :::*

//配置nginx代理
[root@130 conf]# vim nginx.conf
	upstream yy.com{
       	server 192.168.80.128;
       	server 192.168.80.131;
	}
	server {
        listen       80;
        server_name  localhost;
		
        location / {
            proxy_pass http://yy.com;
        }
[root@130 conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@130 conf]# nginx -s reload           

點擊刷新可看到頁面由不同web服務器提供,實現了負載輪詢

在這裏插入圖片描述
在這裏插入圖片描述

發佈了42 篇原創文章 · 獲贊 8 · 訪問量 1105
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章