一站式Nginx實戰指南:從小白到高階運維工程師的進階之路

Nginx 基礎入門

Nginx從入門到入土,本文總結了:什麼是Nginx、Nginx優勢有哪些、如何部署Nginx、Nginx配置檔案含義、Nginx虛擬主機、如何自定義網站、Nginx日誌、個性404頁面、Nginx模組、HTTP&HTTPS、Rewrite重定向,Nginx平滑升級!文章較長,希望可以幫到大家,耐心看完對你有絕對的收穫!如有錯誤請指正~

Nginx 基礎入門

image

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
  • • 編譯安裝
如果需要平滑增加模組使用此安裝

image

  • • yum安裝:nginx: Linux packages
如果不需要指定模組,此安裝會自動安裝很多模組

image

推薦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 -Vnginx version: nginx/1.20.2built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) built with OpenSSL 1.0.2k-fips  26 Jan 2017TLS SNI support enabledconfigure 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配置檔案

image

nginx分為全域性配置和模組配置
相關檔案:/etc/nginx/nginx.conf (主配置檔案)

image

配置檔案內容
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 -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: 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 -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: 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.confserver {    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

image

如果是編譯安裝的nginx還可以修改nginx和版本號,請看我總結在如下博文中👇
👉編譯安裝nginx自定義404介面

image


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 -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: 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         postrotateif [ -f /var/run/nginx.pid ]; thenkill -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 -rn2、 統計每個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 -103、統計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;    }}

image

  • • 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請求,會一直保持這個連線!

image

注意:長連線設定的時間不能太短,不然和短連線沒啥區別!

9.2、隨機主頁模組#

微更新,將主頁設定成隨機頁面,是一種微更新機制
  • • 模組名稱ngx_http_random_index_module
    • • --with-http_random_index_module
  • • 語法random_indexon | off;
  • • 系統預設:關閉狀態(random_index off;)
  • • 作用範圍:location
# 格式示例location / {    random_index on;}
# 示例1、建立主頁目錄mkdir /app2、建立多個主頁,在多個檔案中寫入不同內容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;

image

全部替換:sub_filter_once off;

image


9.4、檔案讀取模組#

👉Nginx官網 檔案讀取模組
  • • 模組名:ngx_http_core_module
  • • sendfile模組:加速伺服器的複製時間,最佳化伺服器的,預設是開啟的;
    • • 語法:sendfileon | off;
  • • tcp_nopush模組:提升了網路傳輸效率,預設是關閉的,當要傳送的資料包積累到一定大小才傳送;
    • • 語法:tcp_nopushon | off;
  • • tcp_nodelay模組: 開啟或關閉nginx使用TCP_NODELAY選項的功能。這個選項僅在將連線轉變為長連線的時候才被啟用。TCP_NODELAY是停用Nagle演算法,即資料包立即傳送出去。由於NagleDelayedACK的原因,資料包的確認資訊需要積攢到兩個時才傳送,長連線情況下,奇數包會造成延時40ms,所以tcp_nodelay會將ack(確認包)立刻發出去。如果不在長連線時,可以關閉此模組,因為ack會被立刻發出去。
    • • 語法:tcp_nodelay on | off; (預設是開啟的)

9.5、檔案壓縮模組#

啟動該模組,使檔案傳輸前進行壓縮,提升傳輸效率;
  • • 模組名稱 :ngx_http_gzip_module
# Directives# 啟用或停用Syntax:    gzipon | off;Default:    gzipoff;Context:    http, server, location, if in location# 壓縮級別,級別越高壓縮時間越長,體積壓的也小Syntax:    gzip_comp_level level;Default:    gzip_comp_level1;(1~9)Context:    http, server,location# gzip versionSyntax:    gzip_http_version 1.0 | 1.1;Default:    gzip_http_version1.1;Context:    http, , server,location# gzip typeSyntax:    gzip_types mime-type ...;Default:    gzip_types text/html;Context:    http,server,location# 靜態壓縮Syntax:    gzip_static on | off | always;Default:    gzip_staticoff;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 | offDefault:    expiresoff# 預設關閉Context:    http, server, location, if in location# 並不是所有的網頁都適合開啟快取,比如12306,前一秒看票還有,後一秒就無了vim /etc/nginx/conf.d/default.conflocation{expires24h# 快取24h}

檢視源影像


9.7、防盜鏈模組#

該模組用於阻止對"引用者"標頭欄位中具有無效值的請求訪問站點。應該記住,使用適當的"Referer"欄位值製造請求非常容易,因此此模組的預期目的不是徹底阻止此類請求,而是阻止常規瀏覽器傳送的大量請求流。還應該考慮到,即使對於有效的請求,常規瀏覽器也可能不會發送"引用者"欄位。ngx_http_referer_module
比如,我不想讓你盜用我伺服器的圖片,那麼就可以透過新增防盜鏈來限制你使用URL來盜用我的圖片;當然也可以透過server_name新增白名單來允許一部分網站來使用;
  • • 模組名:ngx_http_referer_module
# 語法Syntax:    valid_referersnone | blocked | server_names | string ...;Default:    —Context:    server, location# 官網示例valid_referers none blocked server_names*.example.comexample.* www.example.org/galleries/               ~\.google\.;if ($invalid_referer) {return403;}

image


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 Configurationhttp {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:引用限制策略的名稱oneburst=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 {listen80;server_name192.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 {listen80;server_name192.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_exceptSyntax:    deny address | CIDR | unix: | all;Default:    —Context:    http, server, location, limit_except# allow:    允許# deny :    拒絕透過deny和allow,拒絕或者允許某些ip訪問
# 官網示例location / {deny192.168.1.1;  # 拒絕allow192.168.1.0/24;  # 允許allow10.1.1.0/16;  allow2001:0db8::/32;deny  all;   # 拒絕所有}
# 示例1:允許192.168.15.1訪問,不允許其他IP訪問server {listen80;server_name www.Super_Mario.com;allow192.168.15.1;deny all;location / {root /opt/Super_Mario;index index.html;    }}# 示例2:允許192.168.15.0這個網段訪問,不允許其他網段訪問allow192.168.15.0/24;deny all;# 示例3:只允許透過VPN來訪問allow172.16.1.81deny all;

9.9.2、控制使用者訪問#

透過設定使用者名稱密碼來限制訪問
  • • 模組名:ngx_http_auth_basic_module
# 啟用語法Syntax:    auth_basic string | off;Default:    auth_basicoff;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 hammerNew password: Re-type new password: Adding password for user hammer#  檢視[root@web01 conf.d]# cat /etc/nginx/auth hammer:$apr1$fOHr21Vf$zpI/MVxQ452KzP0p10QI10# 將密碼檔案路徑加入配置server {listen80;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 -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful[root@web01 conf.d]# systemctl restart nginx

image


9.10、目錄索引模組#

作用是實現網頁結構目錄索引
  • • 模組名:ngx_http_autoindex_module
# 語法Syntax:    autoindexon | off;Default:    autoindexoff;Context:    http, server,location
# 官網示例location / {autoindexon;}

10、HTTP 協議

👉HTTP|MDN Web官網
HTTP(HyperText Transfer Protocol),超文字傳輸協議,是一種建立在TCP上的無狀態連線,整個基本的工作流程是客戶端傳送一個HTTP請求,說明客戶端想要訪問的資源和請求的動作,服務端收到請求(request)之後,服務端開始處理請求,並根據請求做出相應的動作訪問伺服器資源,最後透過傳送HTTP響應把結果返回給客戶端,其中一個請求的開始到一個響應的結束稱為事務,當一個事物結束後還會在服務端新增一條日誌條目;

11、HTTPS

HTTPS總結在下博文👇
👉HTTPS

12、Nginx rewrite

重定向總結在下博文👇
👉Rewrite

13、Nginx平滑升級

  • • 不需要解除安裝重安裝,在使用者可以正常訪問的情況下,伺服器由低版本升級成高版本;
  • • 想平滑升級,必須是Nginx編譯安裝,編譯安裝可以同時安裝多個版本。不能是yum安裝
  • • 平滑升級是針對未編譯模組新增和版本的更新
# 步驟:1、編譯安裝要更新nginx版本,指定安裝目錄[root@ze ~]# wget https://nginx.org/download/nginx-1.20.1.tar.gz[root@ze ~]# tar -xf nginx-1.20.1.tar.gz# 指定目錄[root@ze nginx-1.20.2]# ./configure --prefix=/opt/nginx1.20.1[root@ze nginx-1.20.2]# make[root@ze nginx-1.20.2]# make install# 補充1:./configure可以指定目錄使用者模組等 ./configure --prefix=/usr/local/app/nginx --user=nginx --group=nginx --with-http_sub_module --with-http_ssl_module --with-http_gzip_static_module --with-pcre=/usr/local/app/nginx/pcre-8.40 --with-zlib=/usr/local/app/nginx/zlib-1.2.11 --with-http_stub_status_module# 補充2:如果使用編譯安裝nginx檢視版本,不能直接使用nginx -v,因為沒有環境變數,必須切換到/usr/local/nginx/sbin目錄下,這個目錄下的nginx是可執行的[root@ze sbin]# /usr/local/nginx/sbin/nginx -vnginx version: nginx/1.20.1[root@ze sbin]# /usr/local/nginx/sbin/nginx -Vnginx version: nginx/1.20.1built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) configure arguments:2、做軟連線:方便版本回退[root@ze sbin]# ln -s /opt/nginx1.20.1 /usr/local/nginx3、新增環境變數,就可以直接使用nginx引數(-v -V -t -c···)PATH=$PATH:/usr/local/nginx/sbin/# [root@ze sbin]# mv/usr/local/nginx/sbin/nginx /usr/sbin/nginx3、檢視舊的nginx主程序號和工作程序號[root@ze ~]# ps aux|grep nginx root       1455  0.0  0.1  46504  1184 ?        Ss   11:36   0:00nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf補:啟動程式碼格式:nginx安裝目錄地址 -c nginx配置檔案地址4、工作完畢重啟程式[root@ze ~]# kill -USR2 1455 (程序號)Nginx版本回退只需要將軟連線刪除,重新將指定的版本軟連線即可rm -rf /usr/local/nginxln -s /opt/nginx1.20.1 /usr/local/nginx

連結:https://www.cnblogs.com/48xz/p/15781821.html
(版權歸原作者所有,侵刪)
文末福利
就目前來說,傳統運維衝擊年薪30W+的轉型方向就是SRE&DevOps崗位。
為了幫助大家早日擺脫繁瑣的基層運維工作,給大家整理了一套高階運維工程師必備技能資料包,內容有多詳實豐富看下圖!
共有 20 個模組
1.38張最全工程師技能圖譜
2.面試大禮包
3.Linux書籍
4.go書籍
······
6.自動化運維工具
18.訊息佇列合集
 以上所有資料獲取請掃碼
備註:最新運維資料
100%免費領取
(後臺不再回復,掃碼一鍵領取


相關文章