nginx工作原理及配置
模塊與工作原理
nginx由內核和模塊組成。其中,內核的設計非常微小和簡潔,完成的工作也非常簡單,僅僅通過查找配置文件將客戶端請求映射到一個location block(location是nginx配置中的一個指令,用于URL匹配),而在這個location中所配置的每個指令將會啟動不同的模塊去完成相應的工作。
模塊分類
nginx的模塊從結構上分為核心模塊、基礎模塊和第三方模塊
- HTTP模塊、EVENT模塊和MAIL模塊等屬于核心模塊
- HTTP Access模塊、HTTP FastCGI模塊、HTTP Proxy模塊和HTTP Rewrite模塊屬于基本模塊
- HTTP Upstream模塊、Request Hash模塊、Notice模塊和HTTP Access Key模塊屬于第三方模塊
用戶根據自己的需要開發的模塊都屬于第三方模塊。
nginx模塊從功能上分為三類,分別是:
- Handlers(處理器模塊)。此類模塊直接處理請求,并進行輸出內容和修改headers信息等操作。handlers處理器模塊一般只能有一個
- Filters(過濾器模塊)。此類模塊主要對其他處理器模塊輸出的內容進行修改操作,最后由nginx輸出
- Proxies(代理器模塊)。就是nginx的HTTP Upstream之類的模塊,這些模塊主要與后端一些服務比如fastcgi等操作交互,實現服務代理和負載均衡等功能
nginx模塊分為:核心模塊、事件模塊、標準Http模塊、可選Http模塊、郵件模塊、第三方模塊和補丁等
nginx基本模塊:所謂基本模塊,指的是nginx默認的功能模塊,它們提供的指令,允許你使用定義nginx基本功能的變量,在編譯時不能被禁用,包括:
- 核心模塊:基本功能和指令,如進程管理和安全。常見的核心模塊指令,大部分是放置在配置文件的頂部
- 事件模塊:在Nginx內配置網絡使用的能力。常見的events(事件)模塊指令,大部分是放置在配置文件的頂部
- 配置模塊:提供包含機制
更多的指令,請參考nginx官方文檔
nginx的工作原理
nginx的模塊直接被編譯進nginx,因此屬于靜態編譯方式。
啟動nginx后,nginx的模塊被自動加載,與Apache不一樣,首先將模塊編譯為一個so文件,然后在配置文件中指定是否進行加載。
在解析配置文件時,nginx的每個模塊都有可能去處理某個請求,但是同一個處理請求只能由一個模塊來完成。
nginx的進程架構:
啟動nginx時,會啟動一個Master進程,這個進程不處理任何客戶端的請求,主要用來產生worker線程,一個worker線程用來處理n個request。
worker 進程中,ngx_worker_process_cycle()函數就是這個無限循環的處理函數。在這個函數中,一個請求的簡單處理流程如下:
多進程模型的處理方式:
- 首先,master進程一開始就會根據我們的配置,來建立需要listen的網絡socket fd,然后fork出多個worker進程。
- 其次,根據進程的特性,新建立的worker進程,也會和master進程一樣,具有相同的設置。因此,其也會去監聽相同ip端口的套接字socket fd。
然后,這個時候有多個worker進程都在監聽同樣設置的socket fd,意味著當有一個請求進來的時候,所有的worker都會感知到。這樣就會產生所謂的“驚群現象”。為了保證只會有一個進程成功注冊到listenfd的讀事件,nginx中實現了一個“accept_mutex”類似互斥鎖,只有獲取到這個鎖的進程,才可以去注冊讀事件。其他進程全部accept 失敗。 - 最后,監聽成功的worker進程,讀取請求,解析處理,響應數據返回給客戶端,斷開連接,結束。因此,一個request請求,只需要worker進程就可以完成。
nginx模塊一次常規的HTTP請求和響應的過程
一個典型的HTTP處理周期:
7. 客戶端發送HTTP請求
8. Nginx基于配置文件中的位置選擇一個合適的處理模塊
9. (如果有)負載均衡模塊選擇一臺后端服務器
10. 處理模塊進行處理并把輸出緩沖放到第一個過濾模塊上
11. 第一個過濾模塊處理后輸出給第二個過濾模塊
12. 然后第二個過濾模塊又到第三個
13. 依此類推 –> 最后把響應發給客戶端。
Nginx本身做的工作實際很少,當它接到一個HTTP請求時,它僅僅是通過查找配置文件將此次請求映射到一個location block,而此location中所配置的各個指令則會啟動不同的模塊去完成工作,因此模塊可以看做Nginx真正的勞動工作者。
基本的WEB服務請求步驟
nginx部署
nginx的安裝
# 關閉防火墻和selinux [root@localhost ~]# systemctl disable --now firewalld Removed /etc/systemd/system/multi-user.target.wants/firewalld.service. Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service. [root@localhost ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config [root@localhost ~]# reboot [root@localhost ~]# getenforce 0 Disabled # 創建系統用戶nginx [root@localhost ~]# useradd -r -M -s /sbin/nologin nginx # 安裝依賴環境 [root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ vim wget make [root@localhost ~]# yum -y groups mark install 'Development Tools' # 創建日志存放目錄 [root@localhost ~]# mkdir -p /var/log/nginx [root@localhost ~]# chown -R nginx.nginx /var/log/nginx # 下載nginx [root@localhost ~]# cd /usr/src/ [root@localhost src]# wget http://nginx.org/download/nginx-1.12.0.tar.gz # 編譯安裝 [root@localhost src]# ls debug kernels nginx-1.12.0.tar.gz [root@localhost src]# tar xf nginx-1.12.0.tar.gz [root@localhost src]# cd nginx-1.12.0 [root@localhost nginx-1.12.0]# ./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 [root@localhost nginx-1.12.0]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install # 配置環境變量 [root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh [root@localhost ~]# . /etc/profile.d/nginx.sh# 啟動nginx [root@localhost ~]# nginx [root@localhost ~]# ss -anlt State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 0.0.0.0:80 0.0.0.0:* LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 128 [::]:22 [::]:* # 寫service文件讓nginx開機自啟 [root@localhost ~]# cat > /usr/lib/systemd/system/nginx.service <<EOF [Unit] Description=nginx After=network.target[Service] Type=forking ExecStart=/usr/local/nginx/sbin/nginx ExecReload=/usr/local/nginx/sbin/nginx -s reload ExecStop=/usr/local/nginx/sbin/nginx -s quit PrivateTmp=true[Install] WantedBy=multi-user.target EOF [root@localhost ~]# systemctl daemon-reload [root@localhost ~]# systemctl enable --now nginx Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service. Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.nginx的配置文件詳解
主配置文件:/usr/local/nginx/conf/nginx.conf
- 默認啟動nginx時,使用的配置文件是:安裝路徑/conf/nginx.conf文件
- 可以在啟動nginx時通過-c選項來指定要讀取的配置文件
nginx常見的配置文件及其作用
| nginx.conf | nginx的基本配置文件 |
| mime.types | MIME類型關聯的擴展文件 |
| fastcgi.conf | 與fastcgi相關的配置 |
| proxy.conf | 與proxy相關的配置 |
| sites.conf | 配置nginx提供的網站,包括虛擬主機 |
nginx.conf的內容分為以下幾段:
- main配置段:全局配置段。其中main配置段中可能包含event配置段
- event {}:定義event模型工作特性
- http {}:定義http協議相關的配置
配置指令:要以分號結尾,語法格式如下:
支持使用變量:
- 內置變量:模塊會提供內建變量定義
- 自定義變量:set var_name value
用于調試、定位問題的配置參數
是否以守護進程方式運行Nginx
守護進程(daemon)是脫離終端并且在后臺運行的進程。它脫離終端是為了避免進程執行過程中的信息在任何終端上顯示,這樣一來,進程也不會被任何終端所產生的信息所打斷。Nginx毫無疑問是一個需要以守護進程方式運行的服務,因此,默認都是以這種方式運行的。
正常運行必備的配置參數
不過Nginx還是提供了關閉守護進程的模式,之所以提供這種模式,是為了方便跟蹤調試Nginx,畢竟用gdb調試進程時最煩瑣的就是如何繼續跟進fork出的子進程了。
# user USERNAME [GROUPNAME] //指定允許worker進程的用戶和組 [root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf user nginx nginx;# pid /path/to/pid_file //指定nginx守護進程的pid文件 [root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf pid logs/nginx.pid; [root@localhost ~]# ls /usr/local/nginx/logs/ nginx.pid [root@localhost ~]# systemctl stop nginx.service [root@localhost ~]# ls /usr/local/nginx/logs/# worker_rlimit_nofile number //設置所有woker進程最大可以打開的文件數,默認1024# worker_rlimit_core size //指明所有worker進程所能夠使用的總體的最大核心文件大小,保持默認即可優化性能的配置參數
worker_processes n; //啟動n個worker進程,這里的n為了避免上下文切換,通常設置為cpu總核心數-1或等于總核心數 worker_cpu_affinity cpumask ...; //將進程綁定到某cpu中,避免頻繁刷新緩存 //cpumask:使用8位二進制表示cpu核心,如:0000 0001 //第一顆cpu核心0000 0010 //第二顆cpu核心0000 0100 //第三顆cpu核心0000 1000 //第四顆cpu核心0001 0000 //第五顆cpu核心0010 0000 //第六顆cpu核心0100 0000 //第七顆cpu核心1000 0000 //第八顆cpu核心#查看cpu [root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf worker_processes 3; worker_cpu_affinity 0001 0010 0100; [root@localhost ~]# systemctl restart nginx.service [root@localhost ~]# ps -ef | grep nginx root 1571 1 0 23:13 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx nginx 1572 1571 0 23:13 ? 00:00:00 nginx: worker process nginx 1573 1571 0 23:13 ? 00:00:00 nginx: worker process nginx 1574 1571 0 23:13 ? 00:00:00 nginx: worker process root 1576 1485 0 23:13 pts/0 00:00:00 grep --color=auto nginx[root@localhost ~]# top top - 23:31:29 up 22 min, 1 user, load average: 0.00, 0.00, 0.00 Tasks: 223 total, 1 running, 222 sleeping, 0 stopped, 0 zombie %Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st MiB Mem : 3752.0 total, 3300.8 free, 216.8 used, 234.4 buff/cache MiB Swap: 4044.0 total, 4044.0 free, 0.0 used. 3305.5 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1 root 20 0 242256 10628 8180 S 0.0 0.3 0:00.92 systemd 2 root 20 0 0 0 0 S 0.0 0.0 0:00.00 kthreadd 3 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 rcu_gp #按shift+f ,輸入nginx,回車Locate string nginxPID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1485 root 20 0 26516 4928 3452 S 0.0 0.1 0:00.03 bash 1571 root 20 0 80256 1092 56 S 0.0 0.0 0:00.00 nginx 1572 nginx 20 0 111708 6276 4700 S 0.0 0.2 0:00.00 nginx 1573 nginx 20 0 111708 6276 4700 S 0.0 0.2 0:00.00 nginx 1574 nginx 20 0 111708 6276 4700 S 0.0 0.2 0:00.00 nginx # 按f, 將光標移到 P = Last Used Cpu (SMP) Fields Management for window 1:Def, whose current sort field is %CPUNavigate with Up/Dn, Right selects for move then <Enter> or Left commits,'d' or <Space> toggles display, 's' sets sort. Use 'q' or <Esc> to end!* PID = Process Id WCHAN = Sleeping in Function * USER = Effective User Name Flags = Task Flags <sched.h> * PR = Priority CGROUPS = Control Groups * NI = Nice Value SUPGIDS = Supp Groups IDs * VIRT = Virtual Image (KiB) SUPGRPS = Supp Groups Names * RES = Resident Size (KiB) TGID = Thread Group Id * SHR = Shared Memory (KiB) OOMa = OOMEM Adjustment * S = Process Status OOMs = OOMEM Score current * %CPU = CPU Usage ENVIRON = Environment vars * %MEM = Memory Usage (RES) vMj = Major Faults delta * TIME+ = CPU Time, hundredths vMn = Minor Faults delta * COMMAND = Command Name/Line USED = Res+Swap Size (KiB) PPID = Parent Process pid nsIPC = IPC namespace Inode UID = Effective User Id nsMNT = MNT namespace Inode RUID = Real User Id nsNET = NET namespace Inode RUSER = Real User Name nsPID = PID namespace Inode SUID = Saved User Id nsUSER = USER namespace InodeSUSER = Saved User Name nsUTS = UTS namespace Inode GID = Group Id LXC = LXC container name GROUP = Group Name RSan = RES Anonymous (KiB) PGRP = Process Group Id RSfd = RES File-based (KiB)TTY = Controlling Tty RSlk = RES Locked (KiB) TPGID = Tty Process Grp Id RSsh = RES Shared (KiB) SID = Session Id CGNAME = Control Group name nTH = Number of Threads NU = Last Used NUMA node P = Last Used Cpu (SMP) TIME = CPU Time SWAP = Swapped Size (KiB) CODE = Code Size (KiB) DATA = Data+Stack (KiB) nMaj = Major Page Faults nMin = Minor Page Faults nDRT = Dirty Pages Count # 空格選擇,按qPID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND P1571 root 20 0 80256 1092 56 S 0.0 0.0 0:00.00 nginx 21572 nginx 20 0 111708 6276 4700 S 0.0 0.2 0:00.00 nginx 01573 nginx 20 0 111708 6276 4700 S 0.0 0.2 0:00.00 nginx 11574 nginx 20 0 111708 6276 4700 S 0.0 0.2 0:00.00 nginx 2timer_resolution interval; //計時器解析度。降低此值,可減少gettimeofday()系統調用的次數 worker_priority number; //指明worker進程的nice值 number取19~-20,數值越低優先級越高 [root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf worker_priority -20; [root@localhost ~]# systemctl restart nginx.service [root@localhost ~]# ps -elf |grep nginx 1 S root 1750 1 0 80 0 - 20064 - 00:21 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx 5 S nginx 1751 1750 0 60 -20 - 27927 do_epo 00:21 ? 00:00:00 nginx: worker process 5 S nginx 1752 1750 0 60 -20 - 27927 do_epo 00:21 ? 00:00:00 nginx: worker process 5 S nginx 1753 1750 0 60 -20 - 27927 do_epo 00:21 ? 00:00:00 nginx: worker process 0 S root 1756 1485 0 80 0 - 3086 - 00:22 pts/0 00:00:00 grep --color=auto nginx事件相關的配置:event{}段中的配置參數
accept_mutex {off|on}; //master調度用戶請求至各worker進程時使用的負載均衡鎖;on表示能讓多個worker輪流地、序列化地去響應新請求 lock_file file; //accept_mutex用到的互斥鎖鎖文件路徑 use [epoll | rtsig | select | poll]; //指明使用的事件模型,建議讓nginx自行選擇 worker_connections #; //每個進程能夠接受的最大連接數[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf events {worker_connections 10240; }[root@localhost ~]# dnf -y install httpd-tools [root@localhost ~]# ab -n 3000 http://192.168.8.132/index.html This is ApacheBench, Version 2.3 <$Revision: 1843412 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/Benchmarking 192.168.8.132 (be patient) Completed 300 requests Completed 600 requests Completed 900 requests Completed 1200 requests Completed 1500 requests Completed 1800 requests Completed 2100 requests Completed 2400 requests Completed 2700 requests Completed 3000 requests Finished 3000 requestsServer Software: nginx/1.20.1 Server Hostname: 192.168.111.141 Server Port: 80Document Path: /index.html Document Length: 612 bytesConcurrency Level: 1 Time taken for tests: 0.376 seconds Complete requests: 3000 Failed requests: 0 Total transferred: 2535000 bytes HTML transferred: 1836000 bytes Requests per second: 7974.21 [#/sec] (mean) Time per request: 0.125 [ms] (mean) Time per request: 0.125 [ms] (mean, across all concurrent requests) Transfer rate: 6580.28 [Kbytes/sec] receivedConnection Times (ms)min mean[+/-sd] median max Connect: 0 0 0.0 0 0 Processing: 0 0 0.0 0 1 Waiting: 0 0 0.0 0 1 Total: 0 0 0.0 0 1Percentage of the requests served within a certain time (ms)50% 066% 075% 080% 090% 095% 098% 099% 0100% 1 (longest request)網絡連接相關的配置參數
keepalive_timeout number; //長連接的超時時長,默認為65s keepalive_requests number; //在一個長連接上所能夠允許請求的最大資源數 keepalive_disable [msie6|safari|none]; //為指定類型的UserAgent禁用長連接 tcp_nodelay on|off; //是否對長連接使用TCP_NODELAY選項,為了提升用戶體驗,通常設為on client_header_timeout number; //讀取http請求報文首部的超時時長 client_body_timeout number; //讀取http請求報文body部分的超時時長 send_timeout number; //發送響應報文的超時時長fastcgi的相關配置參數
# LNMP: php需啟用fpm模型 location ~ \.php$ {root html;fastcgi_pass 127.0.0.1:9000; //定義反向代理fastcgi_index index.php;fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; //.php文件路徑include fastcgi_params; }nginx.conf配置文件案例
更改默認端口號以及進程數和指定特定配置文件
報錯
解決方法
錯誤頁面配置
[root@localhost conf]# vim nginx.conf error_page 404 /404.html; // 把這一行的注釋取消 [root@localhost html]# vim 404.html<html> <head> <title>test</title> </head> <body> <a href="http://www.baidu.com">baidu</a> </body> </html> [root@localhost html]# systemctl restart nginx平滑升級加echo功能獲取現有的程序編譯的參數 -V
localtion配置
通過指定模式來與客戶端請求的URI相匹配
功能:允許根據用戶請求的URI來匹配定義的各location,匹配到時,此請求將被相應的location配置塊中的配置所處理,例如做訪問控制等功能
語法:location [ 修飾符 ] pattern {…}
常用修飾符:
| = | 精確匹配 |
| ~ | 正則表達式模式匹配,區分大小寫 |
| ~* | 正則表達式模式匹配,不區分大小寫 |
| ^~ | 前綴匹配,類似于無修飾符的行為,也是以指定模塊開始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正則表達式 |
| @ | 定義命名location區段,這些區段客戶端不能訪問,只可以由內部產生的請求來訪問,如try_files或error_page等 |
= : 表示必須與指定模式精確匹配
location = /testa {echo "test2";} [root@localhost ~]# curl 192.168.111.141/testa test2 [root@localhost ~]# curl 192.168.111.141/testa?abc test2~:表示指定的正則表達式要區分大小寫,如:
abclocation ~ ^/abc$ {echo "abc";} [root@localhost ~]# curl 192.168.111.141/abc abc [root@localhost ~]# curl 192.168.111.141/abc?abc abc~*:表示指定的正則表達式不區分大小寫,如:
location ~* ^/abc$ {echo "abc";} [root@localhost ~]# curl 192.168.8.137/abc abc [root@localhost ~]# curl 192.168.8.137/ABC abc [root@localhost ~]# curl 192.168.8.137/abc?ABC abc查找順序和優先級:
優先級次序如下:
訪問配置
用于location段
allow:設定允許哪臺或哪些主機訪問,多個參數間用多個allow
deny:設定禁止哪臺或哪些主機訪問,多個參數間用多個deny
用戶認證
auth_basic "歡迎信息"; auth_basic_user_file "/path/to/user_auth_file"user_auth_file內容格式為:
username:password這里的密碼為加密后的密碼串,建議用htpasswd來創建此文件:
[root@localhost ~]# yum -y install httpd-tools [root@localhost ~]# htpasswd -c -m /usr/local/nginx/conf/.pass admin New password: Re-type new password: Adding password for user admin[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation / {auth_basic "Welcome";auth_basic_user_file "conf/.pass";root html;index index.html index.htm;}
https配置
生成證書
#生成一對密鑰 [root@localhost ~]# mkdir -p /etc/pki/CA [root@localhost ~]# cd /etc/pki/CA/ [root@localhost CA]# mkdir private [root@localhost CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048) Generating RSA private key, 2048 bit long modulus (2 primes) ........................+++++ ........................................................................+++++ e is 65537 (0x010001)#生成自簽署證書 [root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365 You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:CN State or Province Name (full name) []:HB Locality Name (eg, city) [Default City]:WH Organization Name (eg, company) [Default Company Ltd]:runtime Organizational Unit Name (eg, section) []:runtime Common Name (eg, your name or your server's hostname) []:test.neawalke.com Email Address []:1@2.com[root@localhost CA]# mkdir certs newcerts crl [root@localhost CA]# touch index.txt && echo 01 > serial#創建證書存放位置 [root@localhost CA]# mkdir /usr/local/nginx/conf/ssl#生成密鑰 [root@localhost ~]# cd /usr/local/nginx/conf/ssl/ [root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048) Generating RSA private key, 2048 bit long modulus (2 primes) ......+++++ ..............+++++ e is 65537 (0x010001)#生成證書簽署請求 [root@localhost ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr Ignoring -days; not generating a certificate You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:CN State or Province Name (full name) []:HB Locality Name (eg, city) [Default City]:WH Organization Name (eg, company) [Default Company Ltd]:runtime Organizational Unit Name (eg, section) []:runtime Common Name (eg, your name or your server's hostname) []:test.neawalke.com Email Address []:1@2.comPlease enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []:#修改nginx配置文件 [root@localhost ~]# vim /usr/local/nginx/conf/nginx.confserver {listen 443 ssl;server_name test.neawalke.com;ssl_certificate ssl/nginx.crt;ssl_certificate_key ssl/nginx.key;ssl_session_cache shared:SSL:1m;ssl_session_timeout 5m;ssl_ciphers HIGH:!aNULL:!MD5;ssl_prefer_server_ciphers on;location / {root html;index index.html index.htm;}}#CA簽署客戶端提交上來的證書 [root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365 Using configuration from /etc/pki/tls/openssl.cnf Check that the request matches the signature Signature ok Certificate Details:Serial Number: 1 (0x1)ValidityNot Before: Oct 27 15:46:45 2021 GMTNot After : Oct 27 15:46:45 2022 GMTSubject:countryName = CNstateOrProvinceName = HBorganizationName = runtimeorganizationalUnitName = runtimecommonName = test.neawalke.comemailAddress = 1@2.comX509v3 extensions:X509v3 Basic Constraints: CA:FALSENetscape Comment: OpenSSL Generated CertificateX509v3 Subject Key Identifier: DB:C0:67:A9:96:4F:D8:67:60:8D:C0:6E:E7:B9:96:A9:70:7A:0E:62X509v3 Authority Key Identifier: keyid:E6:F5:AE:F8:57:F4:37:2F:EE:29:36:75:E9:CB:0E:45:FE:80:8A:72Certificate is to be certified until Oct 27 15:46:45 2022 GMT (365 days) Sign the certificate? [y/n]:y1 out of 1 certificate requests certified, commit? [y/n]y Write out database with 1 new entries Data Base Updated#當需兩臺服務器實現https,需做如下操作 //客戶端把證書簽署請求文件發送給CA scp httpd.csr root@CA端IP:/root//CA把簽署好的證書httpd.crt發給客戶端 scp httpd.crt root@客戶端IP:/etc/httpd/ssl/開啟狀態界面
# 開啟status [root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation /status {stub_status;}
狀態頁面:
| Active connections 2 | 當前所有處于打開狀態的連接數 |
| accepts | 總共處理了多少個連接 |
| handled | 成功創建多少握手 |
| requests | 總共處理了多少個請求 |
| Reading | nginx讀取到客戶端的Header信息數,表示正處于接收請求狀態的連接數 |
| Writing | nginx返回給客戶端的Header信息數,表示請求已經接收完成且正處于處理請求或發送響應的過程中的連接數 |
| Waiting | 開啟keep-alive的情況下,這個值等于active - (reading + writing),意思就是Nginx已處理完正在等候下一次請求指令的駐留連接 |
狀態頁面監控
環境:
| zabbix | 192.168.111.141 | zabbix_server |
| server | 192.168.111.142 | zabbix_agent、nginx |
rewrite
URL重定向 #語法:rewrite regex replacement flag;rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;此處的$1用于引用(.*.jpg)匹配到的內容,又如: rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect; [root@localhost html]# mv images img [root@localhost html]# ls 404.html 50x.html img index.html [root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation /images {rewrite ^/images/(.*\.jpg)$ /img/$1 break;}
常見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)
#使用last,當前匹配結束時,繼續下一個匹配 [root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation /images {rewrite ^/images/(.*\.jpg)$ /img/$1 last;}location /img {rewrite ^/img/(.*)$ https://www.baidu.com/ last;}if
語法:if (condition) {…}
應用場景:
- server段
- location段
常見的condition
- 變量名(變量值為空串,或者以“0”開始,則為false,其它的均為true)
- 以變量為操作數構成的比較表達式(可使用=,!=類似的比較操作符進行測試)
- 正則表達式的模式匹配操作
~:區分大小寫的模式匹配檢查
~:不區分大小寫的模式匹配檢查
!和!:對上面兩種測試取反 - 測試指定路徑為文件的可能性(-f,!-f)
- 測試指定路徑為目錄的可能性(-d,!-d)
- 測試文件的存在性(-e,!-e)
- 檢查文件是否有執行權限(-x,!-x)
Examples:
if ($http_user_agent ~ MSIE) {rewrite ^(.*)$ /msie/$1 break; }if ($http_cookie ~* "id=([^;]+)(?:;|$)") {set $id $1; }if ($request_method = POST) {return 405; }if ($slow) {limit_rate 10k; }if ($invalid_referer) {return 403; }nginx實現動靜分離
環境說明:
| rhel-8.2 | 192.168.111.142(nginx) | nginx |
| rhel-8.2 | 192.168.111.141(node1) | lnmp |
| rhel-8.2 | 192.168.111.145(node2) | httpd |
node1主機
安裝nginx
安裝mysql
安裝php
//安裝epel源 [root@node1 ~]# yum -y install epel-release//安裝依賴包 [root@node1 ~]# yum -y install libxml2 libxml2-devel openssl openssl-devel bzip2 bzip2-devel libcurl libcurl-devel libicu-devel libjpeg libjpeg-devel libpng libpng-devel openldap-devel pcre-devel freetype freetype-devel gmp gmp-devel libmcrypt libmcrypt-devel readline readline-devel libxslt libxslt-devel mhash mhash-devel libsqlite3x-devel php-mysqlnd libzip-devel[root@node1 ~]# yum -y install http://mirror.centos.org/centos/8-stream/PowerTools/x86_64/os/Packages/oniguruma-devel-6.8.2-2.el8.x86_64.rpm //下載php安裝包 [root@node1 ~]# wget https://www.php.net/distributions/php-8.0.10.tar.gz --2021-10-29 15:18:03-- https://www.php.net/distributions/php-8.0.10.tar.gz 正在解析主機 www.php.net (www.php.net)... 185.85.0.29, 2a02:cb40:200::1ad 正在連接 www.php.net (www.php.net)|185.85.0.29|:443... 已連接。 已發出 HTTP 請求,正在等待回應... 200 OK 長度:16169042 (15M) [application/octet-stream] 正在保存至: “php-8.0.10.tar.gz”php-8.0.10.tar.gz 100%[===============================================>] 15.42M 190KB/s 用時 35s 2021-10-29 15:18:42 (445 KB/s) - 已保存 “php-8.0.10.tar.gz” [16169042/16169042])[root@node1 ~]# tar xf php-8.0.10.tar.gz -C /usr/local/ //編譯安裝 [root@node1 ~]# cd /usr/local/ [root@node1 local]# ls bin games lib libexec mysql-5.7.34-linux-glibc2.12-x86_64 php-8.0.10 share etc include lib64 mysql nginx sbin src [root@node1 local]# cd php-8.0.10/ [root@node1 php-8.0.10]# ./configure --prefix=/usr/local/php8 --with-config-file-path=/etc --enable-fpm --disable-debug --disable-rpath --enable-shared --enable-soap --with-openssl --enable-bcmath --with-iconv --with-bz2 --enable-calendar --with-curl --enable-exif --enable-ftp --enable-gd --with-jpeg --with-zlib-dir --with-freetype --with-gettext --enable-mbstring --enable-pdo --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-readline --enable-shmop --enable-simplexml --enable-sockets --with-zip --enable-mysqlnd-compression-support --with-pear --enable-pcntl --enable-posix [root@node1 php-8.0.10]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install //安裝后配置 [root@node1 php-8.0.10]# echo 'export PATH=/usr/local/php8/bin:$PATH' > /etc/profile.d/php.sh [root@node1 php-8.0.10]# source /etc/profile.d/php.sh [root@node1 php-8.0.10]# which php /usr/local/php8/bin/php //配置php-fpm [root@node1 php-8.0.10]# cp php.ini-production /etc/php.ini cp:是否覆蓋'/etc/php.ini'? y [root@node1 php-8.0.10]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm [root@node1 php-8.0.10]# chmod +x /etc/rc.d/init.d/php-fpm [root@node1 php-8.0.10]# cp /usr/local/php8/etc/php-fpm.conf.default /usr/local/php8/etc/php-fpm.conf [root@node1 php-8.0.10]# cp /usr/local/php8/etc/php-fpm.d/www.conf.default /usr/local/php8/etc/php-fpm.d/www.conf [root@node1 php-8.0.10]# service php-fpm start Starting php-fpm done [root@node1 php-8.0.10]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 127.0.0.1:9000 0.0.0.0:* LISTEN 0 128 0.0.0.0:80 0.0.0.0:* LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 80 *:3306 *:* LISTEN 0 128 [::]:22 [::]:* //使用service控制nginx [root@node1 php-8.0.10]# vim /usr/lib/systemd/system/php-fpm.service [root@node1 php-8.0.10]# service php-fpm stop Gracefully shutting down php-fpm . done [root@node1 php-8.0.10]# cat /usr/lib/systemd/system/php-fpm.service [Unit] Description=php server daemon After=network.target[Service] Type=forking ExecStart=/etc/init.d/php-fpm start ExecStop=/etc/init.d/php-fpm stop ExecReload=/bin/kill -HUP $MAINPID[Install] WantedBy=multi-user.target[root@node1 php-8.0.10]# systemctl daemon-reload [root@node1 php-8.0.10]# systemctl enable --now php-fpm.service Synchronizing state of php-fpm.service with SysV service script with /usr/lib/systemd/systemd-sysv-install. Executing: /usr/lib/systemd/systemd-sysv-install enable php-fpm Created symlink /etc/systemd/system/multi-user.target.wants/php-fpm.service → /usr/lib/systemd/system/php-fpm.service. //創建php訪問界面 [root@node1 ~]# vim /usr/local/nginx/html/index.php [root@node1 ~]# cat /usr/local/nginx/html/index.php <?phpphpinfo(); ?> 修改nginx配置文件 [root@node1 ~]# vim /usr/local/nginx/conf/nginx.conf43 location / {44 root html;45 index index.php index.html index.htm; //修改這一行46 }65 location ~ \.php$ {66 root html;67 fastcgi_pass 127.0.0.1:9000;68 fastcgi_index index.php;69 fastcgi_param SCRIPT_FILENAME $Document_Root$fastcgi_script_name; //修改這一行70 include fastcgi_params;71 } [root@node1 ~]# systemctl restart nginx.service
node2主機
nginx主機
在瀏覽器輸入nginx主機IP訪問的是靜態資源
在瀏覽器輸入nginx主機IP+/index.php訪問的是動態資源
總結
以上是生活随笔為你收集整理的nginx工作原理及配置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ADO.NET 快速入门(十五):ADO
- 下一篇: DataGridView数据导入到Exc