1、Nginx簡介
百度解釋:Nginx是一款輕量級的Web 服務器/反向代理服務器及電子郵件(IMAP/POP3)代理服務器,在BSD-like 協議下發行。其特點是占有內存少,并發能力強,事實上nginx的并發能力在同類型的網頁服務器中表現較好,中國大陸使用nginx網站用戶有:百度、京東、新浪、網易、騰訊、淘寶等。
總結:Nginx(engine x)是一個高性能的HTTP(解決C10k的問題)和反向代理服務器,能夠實現動靜分離技術(動態請求和靜態請求),也是一個IMAP/POP3/SMTP服務器,
1.1、相關名詞解釋#
HTTP:HTTP的服務器端實現程序有httpd、nginx等,而且nginx支持高并發!HTTP
反向代理:反向代理服務器位于用戶與目標服務器之間,但是對于用戶而言,反向代理服務器就相當于目標服務器,即用戶直接訪問反向代理服務器就可以獲得目標服務器的資源。同時,用戶不需要知道目標服務器的地址,也無須在用戶端作任何設定。反向代理服務器通常可用來作為Web加速,即使用反向代理作為Web服務器的前置機來降低網絡和服務器的負載,提高訪問效率。反向代理
SMTP:SMTP是一種提供可靠且有效的電子郵件傳輸的協議。(非重點)
Nginx官網
2、Nginx優勢
nginx優勢:高并發、I/O多路復用、epoll模型:異步且非阻塞
- I/O多路復用(重點)
- 理論:I是input輸入,O是output輸出,nginx的I/O多路復用,提高了服務器的吞吐能力,同一個線程里面,通過開關的方式,來同時傳輸多個I/O流,比如你去幫同事解決問題,A同事問你錯誤原因,B同時問你怎么安裝的問題,你同時去幫他們解決;
- 技術分類:select、poll、epoll(epoll模塊實現I/O多路復用)
- 特點:異步、非阻塞特點比喻:同步:比如AB石頭剪刀布同時出為同步異步:石頭剪刀布不同時出異步阻塞:去上廁所,不上完廁所不去干別的事非阻塞:廁所人多可以先去忙別的
- 時分多路復用:時分多路復用(Time-Division Multiplexing,TDM)是一種數字或者模擬(較罕見)的多路復用技術,比如CPU的分時計算,你想去聽歌或者看電影,CPU需要不斷的切換去處理你的個人需求,把時間分成塊,只不過處理的比較快,個人感覺不到。
- 頻分多路復用:頻分多路復用,是在適于某種傳輸媒質的傳輸頻帶內,若干個頻譜互不重疊的信號一并傳輸的方式,比如現在既可以打電話也可以上網,就是用到了此技術。
3、Nginx部署
Nginx官網
選擇download
- 編譯安裝
如果需要平滑增加模塊使用此安裝
- yum安裝:nginx: linux packages
如果不需要指定模塊,此安裝會自動安裝很多模塊
推薦yum安裝,去官網找倉庫,配置文件不需要改,主線版本不要打開~使用穩定版就行
- 如何安裝我總結在此博文Nginx部署
4、Nginx配置文件
查看相關配置文件:rpm -ql nginx
[root@web01 ~]# rpm -ql nginx
/etc/logrotate.d/nginx # 日志輪轉文件*
/etc/nginx/nginx.conf # 總配置文件*
/etc/nginx/conf.d # 子配置文件*
/etc/nginx/conf.d/default.conf #默認網站配置文件 *
/etc/nginx/fastcgi_params # 動態網站模塊文件-Python,php所需的相關變量
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/etc/nginx/mime.types # 文件關聯程序:網站文件類型和相關處理程序
/etc/nginx/modules # nginx模塊文件
/usr/lib/systemd/system/nginx-debug.service # nginx調試程序啟動腳本
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/usr/sbin/nginx # 主程序
/usr/sbin/nginx-debug # 調試程序
# man nginx手冊文件如下
/usr/share/doc/nginx-1.20.2
/usr/share/doc/nginx-1.20.2/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx # 緩存文件
/var/log/nginx # 日志文件
5、Nginx模塊
yum安裝,自帶的模塊剖析
# yum安裝的模塊如下都安裝好了,模塊是固定的,如果想自定義增加模塊使用編譯安裝才可以
[root@web01 sbin]# nginx -V
nginx version: nginx/1.20.2
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments:
--prefix=/etc/nginx # 指定安裝路徑
--sbin-path=/usr/sbin/nginx # 程序文件位置
--modules-path=/usr/lib64/nginx/modules # 模塊路徑的位置
--conf-path=/etc/nginx/nginx.conf # 主配置文件的位置
--error-log-path=/var/log/nginx/error.log # 錯誤日志位置
--http-log-path=/var/log/nginx/access.log # 訪問日志位置
--pid-path=/var/run/nginx.pid # 程序PID
--lock-path=/var/run/nginx.lock # 鎖路徑,防止重復啟動nginx
--http-client-body-temp-path=/var/cache/nginx/client_temp # 緩存
--http-proxy-temp-path=/var/cache/nginx/proxy_temp # 代理緩存
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp # php緩存
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp # python緩存位置
--http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx # 用戶
--group=nginx # 組
--with-compat # 啟動動態模塊兼容
--with-file-aio # 提高性能
--with-threads # 多線程模塊
--with-http_addition_module # 響應之前或者之后追加文本內容
--with-http_auth_request_module # 認證模塊,比如登錄密碼
--with-http_dav_module # 增加上傳PUT,DELETE,MKCOL:創建集合,COPY和MOVE方法)默認情況下為關閉
--with-http_flv_module # NGINX添加MP4、FLV視頻支持模塊
--with-http_gunzip_module # 壓縮模塊
--with-http_gzip_static_module # 壓縮模塊
--with-http_mp4_module # 支持多媒體
--with-http_random_index_module # 隨機主頁
--with-http_realip_module # nginx獲取真實ip模塊
--with-http_secure_link_module # nginx安全下載模塊
--with-http_slice_module # nginx中文文檔
--with-http_ssl_module # 網站加密
--with-http_stub_status_module # 訪問狀態
--with-http_sub_module # nginx替換響應內容
--with-http_v2_module # web2.0技術
# 郵局
--with-mail # 郵件
--with-mail_ssl_module
# 負載均衡反向代理模塊
--with-stream
--with-stream_realip_module
--with-stream_ssl_module
--with-stream_ssl_preread_module
# CPU優化參數等
--with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
編譯安裝如何平滑增加模塊?我總結在此博文
nginx平滑增加模塊
6、Nginx配置文件
nginx分為全局配置和模塊配置
相關文件:/etc/nginx/nginx.conf (主配置文件)
配置文件內容
1、全局/核心塊。配置影響nginx全局的指令。一般有運行nginx服務器的用戶組,nginx進程pid存放路徑,日志存放路徑,配置文件引入,元許生成workerprocess數等。
user nginx; # 指定Nginx的啟動用戶
worker_processes auto; # 開啟nginx的數量,可以自定義,建議和CPu一樣多,2核就寫2個···
error_log /var/log/nginx/error.log notice; # 錯誤日志
pid /var/run/nginx.pid; # 進程號存放路徑
2、events塊,配置影響nginx服務器或與用戶的網絡連接。有每個進程的最大連接數,選取哪種事件驅動模型處理連接請求,是否允許同時接受多個網路連接,開啟多個網絡連接序列化等。
events {
worker_connections 1024; # 進程最大連接數
}
3、http模塊:可以嵌套多個server,配置代理,緩存,日志定義等絕大多數功能和第三方模塊的配置。如文件引入,mime-type定義,日志自定義,是否使用sendfile傳輸文件,連接超時時間,單連接請求數等。
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"'; # 日志格式,可以修改為json
access_log /var/log/nginx/access.log main; # 訪問日志
sendfile on; # 加速訪問、高效讀取文件
#tcp_nopush on; # 優化
keepalive_timeout 65; # 長連接,timeout不能太低,不然和短鏈接一樣
#gzip on; # 壓縮
include /etc/nginx/conf.d/*.conf; # 配置文件
}
4、server塊:配置虛擬主機的相關參數,一個http中可以有多個server
5、location塊:配置請求的路由,以及各種頁面的處理情況
- nginx配置結構分為三層 http > server > location
- http 包含一到多個server, server包含一到多個location
- 配置項的優先級分別是location, server, http
http {
...
access_log /var/logs/nginx/nginx.log;
server {
server_name A;
...
access_log /var/logs/nginx/serverA/nginx.log;
location / {
...
access_log /var/logs/nginx/serverA/localtion/nginx.log;
}
}
}
- 匹配到server A,localtion /時日志會記錄到 /var/logs/nginx/serverA/localtion/nginx.log
- 匹配到server A 其他location時日志會記錄到/var/logs/nginx/serverA/nginx.log
- 默認請求日志記錄到 /var/logs/nginx/nginx.log;
6.1、Location配置優先級#
使用Nginx Location可以控制訪問網站的路徑, 但一個server可以有多個location配置, 多個location的優先級該如何區分,就用到了location配置的優先級~
6.1.1、location匹配符號#
匹配符 |
匹配規則 |
優先級 |
= |
精確匹配 |
1 |
^~ |
以某個字符串開頭 |
2 |
~ |
區分大小寫的正則匹配 |
3 |
~* |
不區分大小寫的正則匹配 |
3 |
/ |
通用匹配,任何請求都會匹配到 |
4 |
=號優先級最高
server {
listen 80;
server_name _;
location ~* /python {
default_type text/html;
return 200 "Location ~*";
}
location ~ /Python {
default_type text/html;
return 200 "Location ~";
}
location ^~ /python {
default_type text/html;
return 200 "Location ^~";
}
location = /python {
default_type text/html;
return 200 "Location =";
}
}
6.2、http、server、location三者關系(通俗理解)#
- http:通俗理解為整個服務器,如果在http下添加配置,那么整個服務器的網站都會受影響,不管是網站A,還是網站B,或者網站中的某一個頁面
- server:通俗理解為服務器中的一個網站,在server中配置,那么受影響的只有該網站;
- location:通俗理解為網站的某一個頁面,如果在location下配置,那么受影響的只有該server的該頁面;
6.3、include : 加載外部的配置項#
相關文件/etc/nginx/conf.d/*.conf
# 重點
server : 網址模塊,每一個server代表一個網站,可以有多個
listen : 監聽的端口
server_name : 定義域名
location {} : 訪問路徑
root : 指定網址路徑
index : 指定網址的索引文件
Nginx配置文件博文
Nginx如何yum安裝和編譯安裝以及配置文件剖析和游戲案例我編寫在如上博文
7、Nginx虛擬主機
三種方式,示例是自己創的網站,只要以.conf都可以被識別
- 相關文件目錄:/etc/nginx/conf.d (子配置文件)
# 默認配置文件/etc/nginx/conf.d/default.conf
[root@web01 conf.d]# cat /etc/nginx/conf.d/default.conf
server {
listen 80; # 端口
server_name localhost; # 域名
#access_log /var/log/nginx/host.access.log main; # 日志和格式
location / {
root /usr/share/nginx/html; # 存放網站目錄,這里是默認網站
index index.html index.htm; # 默認主頁文件名
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
} # 錯誤頁面
}
自定義頁面建議在子配置目錄下創建以.conf結尾的文件
7.1、自定義網站#
# 自定義配置文件
[root@web01 ~]# vim /etc/nginx/conf.d/hammer.conf
server{
listen 80;
server_name www.hammer.com;
location / {
root /opt/Hammer;
index index.html;
}
}
# 創建目錄 /opt/Hammer
[root@web01 ~]# mkdir /opt/Hammer
# 寫入內容
[root@web01 chess]# echo "歡迎來到HammerZe的博客" > /opt/Hammer/index.html
# 測試配置文件
[root@web01 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
# 域名解析
在windows中hosts文件解析
# 重啟服務.
[root@web01 conf.d]# systemctl restart nginx
# 測試是否能訪問
去瀏覽器測試
補充知識:elinks字符瀏覽器,格式:elinks [域名]
7.2、三種方式#
總結在以下博文
三種方式
7.2.1、基于多IP的方式#
# 防止其他配置文件影響,將所有配置文件壓縮
[root@web01 conf.d]# gzip Mario.conf
[root@web01 conf.d]# gzip chess.conf.gz
[root@web01 conf.d]# gzip default.conf.gz
# 編輯配置文件
[root@web01 ~]# cd /etc/nginx/conf.d
[root@web01 conf.d]# vim game.conf
server {
listen 80;
server_name 192.168.15.7;
location / {
root /opt/Super_Mario; # 需要創建
index index.html;
}
}
server {
listen 80;
server_name 172.16.1.7;
location / {
root /opt/chess;
index index.html;
}
}
# 測試配置文件
[root@web01 conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfu
# 重啟服務
[root@web01 conf.d]# systemctl restart nginx
7.2.2、基于多端口的方式#
# 編輯配置文件
[root@web01 conf.d]# vim game1.conf
server {
listen 80;
server_name 192.168.15.7;
location / {
root /opt/Super_Mario;
index index.html;
}
}
server {
listen 81;
server_name 192.168.15.7;
location / {
root /opt/chess;
index index.html;
}
}
7.2.3、基于多域名的方式#
# 編輯配置文件
[root@web01 conf.d]# vim game2.conf
server {
listen 80;
server_name www.Super_Mario.com;
location / {
root /opt/Super_Mario;
index index.html;
}
}
server {
listen 80;
server_name www.chesss.com;
location / {
root /opt/chess;
index index.html;
}
}
# 注意域名不能用chess
2和3其余步驟和1一樣
8、Nginx 日志
8.1、日志配置#
官網文檔:Module ngx_http_log_module (nginx.org)
8.1.1、日志模塊名稱#
ngx_http_log_module
8.1.2、相關指令#
- log_format :日志格式
- access_log :正確訪問進程日志
- error_log:錯誤日志
- open_log_file_cache:日志緩存
8.1.3、日志格式和命令#
相關文件:/etc/nginx/nginx.conf
# 查看nginx的主配置文件
[root@ze nginx]# cat /etc/nginx/nginx.conf
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; # 這里的main格式和上面的main對應
# 配置詳解
$remote_addr:遠程地址,記錄客戶端IP地址
- :分隔符
$remote_user:代表登錄用戶名(沒有就用-代替)
[$time_local] :本地時間
$request:請求方式、類型(post,get···)
request:包括請求方式,訪問文件,連接方式(HTTP/1.1長連接)
$status :狀態碼 (200,404,502·····)
$body_bytes_sent :訪問文件大小
$http_referer:訪問域名,跳轉地址(超鏈接)
$http_user_agent:客戶端標識
$http_x_forwarded_for:真實的客戶端IP(在反向代理中生效,代理地址)
監控日志
- tail -f /var/log/nginx/access.log
- tail -f /var/log/nginx/error.log
8.2、個性化404頁面#
個性化404頁面是用于美化頁面,或者優化操作,提升了用戶的體驗!
# 定義404頁面路徑
[root@ze ze]# vim /etc/nginx/conf.d/zeself.conf
server{
listen 80;
server_name www.zemake.com;
location / {
root /opt/ze;
index index.html zemake.html;
}
error_page 404 /404.html;
location = /404.html {
root /opt/ze;
}
}
# 自定義404界面
[root@ze ze]# vim /opt/ze/404.html
<img src="404.jpg"/ >
# 上傳404個性圖片
[root@ze ze]# ll
-rw-r--r-- 1 root root 84134 Jan 8 14:52 404.jpg
# 重啟
[root@ze ze]# systemctl restart nginx
如果是編譯安裝的nginx還可以修改nginx和版本號,請看我總結在如下博文中
編譯安裝nginx自定義404界面
8.3、日志緩存#
當瀏覽器大量訪問到來時,對于每一條日志記錄,都是先打開文件,再寫入日志,然后關閉,占用了系統的I/O,與業務無關!可以通過open_log_file_cache來設置;(一般不用設置)
- 語法:open_log_file_cache max=1000 inactive=20s min_uses=3 valid=1m;
- 系統默認:open_log_file_cache off;
- 作用范圍:http、server、location
- 參數剖析:
- max 1000指的是日志文件的FD,最大的緩存數量為1000;
- 如果緩存數量超了,min_users3是20秒內小于3次訪問的FD,就給你清掉,結合inactive 20s的時間;
- valid 1m檢查周期為1分鐘。
- 總結:緩存最多1000個,到了極限.每分鐘開始清除掉20秒內小于3次的文件FD(FD:文件關聯),節省了系統的I/O;
# 設置緩存配置
[root@ze conf.d]# cat /etc/nginx/conf.d/zeself.conf
server{
open_log_file_cache max=1000 inactive=20s min_uses=3 valid=1m;
listen 80;
server_name www.zemake.com;
location / {
root /opt/ze;
index index.html zemake.html;
}
error_page 404 /404.html;
location = /404.html {
root /opt/ze;
}
}
[root@ze 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@ze conf.d]# systemctl restart nginx
8.4、日志輪轉 / 切割#
Nginx安裝,會默認啟動日志輪轉,可以通過rpm -ql nginx|grep log過濾出日志輪轉文件;
日志輪轉、切割是為了更好的節省空間
- 日志輪轉文件:/etc/logrotate.d/nginx
- 日志目錄:/var/log/nginx/
[root@ze nginx]# cat /etc/logrotate.d/nginx
/var/log/nginx/*.log { # 針對.log結尾的日志文件
daily # 輪轉周期,以天為單位
missingok # 文件丟失不提示
rotate 52 # 保留52天
compress # 日志輪轉后壓縮,節省資源
delaycompress # 暫緩壓縮
notifempty # 空文件不輪轉
create 640 nginx adm # 日志切割之后創建新文件nginx為數主,adm為數組,權限640
# 下面是切割完重啟
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
8.5、日志分析#
知道日志格式是什么,日志的字段[8.1],統計用戶訪問情況,頁面流量,統計PV,UV···等
# 分析的字段
$remote_addr:遠程地址,記錄客戶端IP地址
$remote_user:代表登錄用戶名(沒有就用-代替)
[$time_local] :本地時間
$request:請求方式、類型(post,get···)
request:包括請求方式,訪問文件,連接方式(HTTP/1.1長連接)
$status :狀態碼 (200,404,502·····)
$body_bytes_sent :訪問文件大小
$http_referer:訪問域名,跳轉地址(超鏈接)
$http_user_agent:客戶端標識
$http_x_forwarded_for:真實的客戶端IP(在反向代理中生效,代理地址)
8.5.1、 PV、UV、IP#
8.5.1.1、簡介#
- PV(Page View)訪問量, 即頁面瀏覽量或點擊量,衡量網站用戶訪問的網頁數量;在一定統計周期內用戶每打開或刷新一個頁面就記錄1次,多次打開或刷新同一頁面則瀏覽量累計 。
- 訪問量指PV指網站頁面的瀏覽量,頁面被刷新一次就計算一次。如果網站被刷新了1000次,那么流量統計工具顯示的PV就是1000
- UV(Unique Visitor)獨立訪客,統計1天內訪問某站點的用戶數(以cookie為依據);訪問網站的一臺電腦客戶端為一個訪客。可以理解成訪問某網站的電腦的數量。網站判斷來訪電腦的身份是通過來訪電腦的cookies實現的。如果更換了IP后但不清除cookies,再訪問相同網站,該網站的統計中UV數是不變的。如果用戶不保存cookies訪問、清除了cookies或者更換設備訪問,計數會加1。00:00-24:00內相同的客戶端多次訪問只計為1個訪客。
- IP(Internet Protocol)獨立IP數,是指1天內多少個獨立的IP瀏覽了頁面,即統計不同的IP瀏覽用戶數量。
8.5.1.2、三者關系#
PV是和IP的數量是成正比的,因為頁面被刷新一次那么PV就會被記錄一次,所以IP越多,說明網站的PV數據也就隨之增多。但是需要注意的是PV并不是訪問網站的用戶數量,而是網站被訪問的頁面數量。因為一個訪問者可以多次刷新頁面,增加PV數量 。
關系 |
描述 |
PV>UV |
頁面訪問數,一定會大于獨立用戶訪問數 |
UV>IP |
10個用戶在同一個局域網使用同一個IP訪問相同網頁,此UV=10,IP=1。 |
IP>UV |
1個用戶網絡頻繁掉線,重復了10次聯網登錄網頁,此時UV=1,IP=10。 |
參考博文:PV、UV、IP
8.5.2、分析案例#
1、 統計一天內訪問最多的10個ip
日期:日/月/年:時:分:秒 -> 01/Sep/2022
grep '日期' [日志路徑] | awk '{arry[$1]++}END{for(i in ips ){print i , arry[i]}}'|sort -k2 -rn
2、 統計每個URL訪問內容總大小($body_bytes_sent)
grep '日期' [日志路徑]| awk '{urls[$7]++;size[$7]+=$10}END{for(i in urls){print "次數" urls[i],"體積" size[i], "內容" i}}'| sort -kl -rn | head -10
3、統計IP訪問狀態碼為404和出現的次數($status)
grep '日期' [日志路徑] | awk '{if($9="404"){ip_code[$1" "$9]++}}END{for(i in ip_code){print i,ip_code[i]l}}'
4、統計前一分鐘的PV量
date=$(date -d '-1 minute'+%Y:9%H:%M); awk -v awkdate=$date '$0 ~ date{it+}END{print i}' /var/log/nginx/access.log
9、Nginx Web 模塊
模塊信息都可以在官網查看,示例等;
Nginx 官網文檔
9.1、連接狀態模塊#
- 模塊名稱:ngx_http_stub_status_module--with-http_stub_status_module
- 語法:stub_status;
- 作用范圍:server,location
如果是編譯安裝的nginx是沒有此模塊的,需要./configure --help查看要安裝的模塊名
# 格式示例
location /basic_status {
stub_status;
}
# 配置文件
server{
# 日志緩存
open_log_file_cache max=1000 inactive=20s min_uses=3 valid=1m;
listen 80;
server_name www.zemake.com;
location / {
root /opt/ze;
index index.html zemake.html; # 網頁根頁面
# stub_status;
}
location /status {
stub_status;
allow all;
}
error_page 404 /404.html;
location = /404.html {
root /opt/ze;
}
}
- Active connections :當前活動的連接數(用戶數)
- server accepts handled requests:服務器接受處理請求
- 2:總連接數
- 2:成功連接數
- 10:總共處理的請求數
- Reading:0 :讀取客戶端Header的信息數,請求頭
- Writing:1:返回給客戶端的Header的信息署,響應頭
- Waiting:1:等待的請求書,開啟了keepalive(長連接)
9.1.1、keepalive長連接#
補充知識:
長連接的存在解決了客戶端和服務端每次通信需要TCP三次握手和四次斷開浪費資源的情況,在使用長連接的情況下,當一個網頁打開完成后,客戶端和服務器之間用于傳輸HTTP數據的TCP連接不會關閉,客戶端再次訪問這個服務器時,會繼續使用這一條已經建立的連接。
如果一直長連接是不是也在浪費資源呢?那么就可以使用Httpd守護進程,來通過keep-alive timeout設置時間參數,Nginx中提供的是keepalive_timeout參數,如果通信建立長連接,當HTTP產生的TCP連接傳輸完最后一個響應,還需要再等待一段時間,就是keepalive_timeout設置的,如果超過這段時間,瀏覽器沒有接收到HTTP的請求,那么才會關閉這個連接,雙方才會回收資源;如果在規定的時間內接收到HTTP請求,會一直保持這個連接!
注意:長連接設置的時間不能太短,不然和短連接沒啥區別!
9.2、隨機主頁模塊#
微更新,將主頁設置成隨機頁面,是一種微更新機制
- 模塊名稱:ngx_http_random_index_module--with-http_random_index_module
- 語法:random_index on | off;
- 系統默認:關閉狀態(random_index off;)
- 作用范圍:location
# 格式示例
location / {
random_index on;
}
# 示例
1、創建主頁目錄
mkdir /app
2、創建多個主頁,在多個文件中寫入不同內容
touch /app{blue.html,green.html,red.html,.yellow.html}
[root@ze app]# cat red.html
<html>
<head>
<title>red color</title>
</head>
<body stytle="background-color:red">
<h1>red color</h1>
</body>
</html>
3、配置文件
location / {
# root /usr/share/nginx/html;
# index index.html index.htm;
root /app;
random_index on;
}
9.3、替換模塊#
網頁內容替換,如果我們用模板生成網站的時候,因為疏漏或者別的原因造成代碼不如意,但是此時因為文件數量巨大,不方便全部重新生成,那么這個時候我們就可以用此模塊來暫時實現糾錯。另一方面,我們也可以利用這個實現服務器端文字過濾的效果。
- 模塊名稱:ngx_http_sub_module--with-http_sub_module
- 使用此模塊是臨時修改,只是為了在網頁出錯的時候給用戶呈現正確的結果
- 語法:**sub_filter** *string* *replacement*;
- 作用范圍:http,server,location
- 啟動替換1:
- 啟動替換2:
# 官網示例
location / {
sub_filter '<a href="http://127.0.0.1:8080/' '<a href="https://$host/';
sub_filter '<img src="http://127.0.0.1:8080/' '<img src="https://$host/';
sub_filter_once on;
}
# 啟動替換1示例
[root@ze conf.d]# vim /etc/nginx/conf.d/default.conf
server {
sub_filter 'nginx' 'blogs';
sub_filter_once on; # 替換一次
# sub_filter_once off; # 全部替換
}
# 將默認的nginx的主頁中,nginx修改為blogs
替換一次:sub_filter_once on;
全部替換:sub_filter_once off;
9.4、文件讀取模塊#
Nginx官網 文件讀取模塊
- 模塊名:ngx_http_core_module
- sendfile模塊:加速服務器的拷貝時間,優化服務器的,默認是開啟的;語法:sendfile on | off;
- tcp_nopush模塊:提升了網絡傳輸效率,默認是關閉的,當要發送的數據包積累到一定大小才發送;語法:tcp_nopush on | off;
- tcp_nodelay模塊: 開啟或關閉nginx使用TCP_NODELAY選項的功能。這個選項僅在將連接轉變為長連接的時候才被啟用。
TCP_NODELAY是禁用Nagle算法,即數據包立即發送出去。由于Nagle和DelayedACK的原因,數據包的確認信息需要積攢到兩個時才發送,長連接情況下,奇數包會造成延時40ms,所以tcp_nodelay會將ack(確認包)立刻發出去。如果不在長連接時,可以關閉此模塊,因為ack會被立刻發出去。語法:tcp_nodelay on | off; (默認是開啟的)
9.5、文件壓縮模塊#
啟動該模塊,使文件傳輸前進行壓縮,提升傳輸效率;
- 模塊名稱 :ngx_http_gzip_module
# Directives
# 啟用或禁用
Syntax: gzip on | off;
Default: gzip off;
Context: http, server, location, if in location
# 壓縮級別,級別越高壓縮時間越長,體積壓的也小
Syntax: gzip_comp_level level;
Default: gzip_comp_level 1;(1~9)
Context: http, server,location
# gzip version
Syntax: gzip_http_version 1.0 | 1.1;
Default: gzip_http_version 1.1;
Context: http, , server,location
# gzip type
Syntax: gzip_types mime-type ...;
Default: gzip_types text/html;
Context: http,server,location
# 靜態壓縮
Syntax: gzip_static on | off | always;
Default: gzip_static off;
Context: http, server, location
# 靜態壓縮官網示例
gzip_static on;
gzip_proxied expired no-cache no-store private auth;
9.6、頁面緩存模塊#
expires起到控制頁面緩存的作用,合理的配置expires可以減少很多服務器的請求要配置expires,可以在http段中或者server段中或者location段中加入。Nginx(expires 緩存減輕服務端壓力);
- 模塊名:ngx_http_headers_module
- 語法:expires [modified] time;expires epoch | max | off;
Syntax: expires [modified] time; # 緩存時間
expires epoch | max | off;
Default: expires off; # 默認關閉
Context: http, server, location, if in location
# 并不是所有的網頁都適合開啟緩存,比如12306,前一秒看票還有,后一秒就無了
vim /etc/nginx/conf.d/default.conf
location{
expires 24h; # 緩存24h
}
9.7、防盜鏈模塊#
該模塊用于阻止對"引用者"標頭字段中具有無效值的請求訪問站點。應該記住,使用適當的"Referer"字段值制造請求非常容易,因此此模塊的預期目的不是徹底阻止此類請求,而是阻止常規瀏覽器發送的大量請求流。還應該考慮到,即使對于有效的請求,常規瀏覽器也可能不會發送"引用者"字段。ngx_http_referer_module;
比如,我不想讓你盜用我服務器的圖片,那么就可以通過添加防盜鏈來限制你使用URL來盜用我的圖片;當然也可以通過server_name添加白名單來允許一部分網站來使用;
- 模塊名:ngx_http_referer_module
# 語法
Syntax: valid_referers none | blocked | server_names | string ...;
Default: —
Context: server, location
# 官網示例
valid_referers none blocked server_names
*.example.com example.* www.example.org/galleries/
~.google.;
if ($invalid_referer) {
return 403;
}
9.7.1、日志格式字段#
- 字段名:$http_referer
日志格式中的http_referer是記錄,訪問點引用的URL。也就是超鏈接的上一級地址。通過這段地址,可以發現一種網絡行為——盜鏈。非法盜鏈會影響站點的正常訪問。通過http_referer模塊可以控制這一點。防止非法盜鏈現象。
9.8、訪問限制模塊#
9.8.1、ngx_http_limit_req_module模塊#
用于限制每個已定義鍵的請求處理速率,特別是來自單個 IP 地址的請求的處理速率,使用"leaky bucket"方法完成限制;
- 模塊名:ngx_http_limit_req_module
# 語法
Syntax: limit_req zone=name [burst=number] [nodelay | delay=number];
Default: —
Context: http, server,location
官網示例
# Example Configuration
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
...
server {
...
location /search/ {
limit_req zone=one burst=5;
}
# 定義剖析
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
# 剖析
limit_req_zone :限制請求
$binary_remote_addr :二進制地址
zone=one:10m :限制策略的名稱:占用10M空間
rate=1r/s:允許每秒1次請求
# 引用剖析
limit_req zone=one burst=5;
# 剖析
limit_req zone=one:引用限制策略的名稱one
burst=5 表示最大延遲請求數量不大于5。如果太過多的請求被限制延遲是不需要的,這時需要使用nodelay參數,服務器會立刻返回503狀態碼。
個人示例
1、控制Nginx連接數
1、安裝ab測試命令
yum install httpd-tools -y
2、ab 參數
-n : 總共需要訪問多少次
-c : 每次訪問多少個
[root@web01 conf.d]# vim game5.conf
# limit_req_zone $remote_addr zone=one:10m rate=1r/s;
limit_conn_zone $remote_addr zone=addr:10m;
server {
listen 80;
server_name 192.168.15.7;
# limit_req zone=one burst=5;
limit_conn addr 1;
location / {
root /opt/Super_Marie;
index index.html;
}
}
9.8.2、ngx_http_limit_conn_module模塊#
- 模塊名:ngx_http_limit_conn_module
ngx_http_limit_conn_module模塊用于限制鏈接(TCP),特別是來自單個IP地址的連接數。不是所有的連接都被計算在內。只有當服務器正在處理一個請求,并且整個請求頭已經被讀取時,連接才會被計數。
# 語法
Syntax: limit_conn zone number;
Default: —
Context: http, server, location
# 官網示例
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
...
server {
...
location /download/ {
limit_conn addr 1;
}
# 個人示例
[root@web01 conf.d]# vim game5.conf
# limit_req_zone $remote_addr zone=one:10m rate=1r/s;
limit_conn_zone $remote_addr zone=addr:10m;
server {
listen 80;
server_name 192.168.15.7;
# limit_req zone=one burst=5;
limit_conn addr 1;
location / {
root /opt/Super_Marie;
index index.html;
}
}
9.9、訪問控制模塊#
9.9.1、控制ip訪問#
- 模塊名:ngx_http_access_module
基于ip操作
Syntax: allow address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except
Syntax: deny address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except
# allow: 允許
# deny : 拒絕
通過deny和allow,拒絕或者允許某些ip訪問
# 官網示例
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:
允許192.168.15.1訪問,不允許其他IP訪問
server {
listen 80;
server_name www.Super_Mario.com;
allow 192.168.15.1;
deny all;
location / {
root /opt/Super_Mario;
index index.html;
}
}
# 示例2:
允許192.168.15.0這個網段訪問,不允許其他網段訪問
allow 192.168.15.0/24;
deny all;
# 示例3:
只允許通過VPN來訪問
allow 172.16.1.81;
deny all;
9.9.2、控制用戶訪問#
通過設置用戶名密碼來限制訪問
- 模塊名:ngx_http_auth_basic_module
# 啟用語法
Syntax: auth_basic string | off;
Default: auth_basic off;
Context: http, server, location, limit_except
# 指定密碼文件
Syntax: auth_basic_user_file file;
Default: —
Context:http,server,location,limit_except
# 官網示例
location / {
auth_basic "closed site";
auth_basic_user_file conf/htpasswd;
}
# 示例:訪問之前需要登錄
# 安裝httpd-tools
[root@web01 conf.d]# yum install httpd-tools -y
# 生成用戶名密碼文件
[root@web01 conf.d]# htpasswd -c /etc/nginx/auth hammer
New password:
Re-type new password:
Adding password for user hammer
# 查看
[root@web01 conf.d]# cat /etc/nginx/auth
hammer:$apr1$fOHr21Vf$zpI/MVxQ452KzP0p10QI10
# 將密碼文件路徑加入配置
server {
listen 80;
server_name www.Super_Mario.com;
auth_basic "hello nginx";
auth_basic_user_file /etc/nginx/auth;
location / {
root /opt/Super_Mario;
index index.html;
}
}
[root@web01 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 conf.d]# systemctl restart nginx
9.10、目錄索引模塊#
作用是實現網頁結構目錄索引
- 模塊名:ngx_http_autoindex_module
# 語法
Syntax: autoindex on | off;
Default:
autoindex off;
Context: http, server,location
# 官網示例
location / {
autoindex on;
}
原文地址
:https://www.cnblogs.com/48xz/p/15781821.html