日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Nginx >内容正文

Nginx

Nginx工作原理

發布時間:2023/12/10 Nginx 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Nginx工作原理 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、nginx簡介

nginx(發音同engine x)是一款輕量級的Web服務器/反向代理服務器及電子郵件(IMAP/POP3)代理服務器,并在一個BSD-like協議下發行。

nginx由俄羅斯的程序設計師Igor Sysoev所開發,最初供俄國大型的入口網站及搜尋引擎Rambler使用。

第一個公開版本0.1.0發布于2004年10月4日。其將源代碼以類BSD許可證的形式發布,因它的穩定性、豐富的功能集、示例配置文件和低系統資源的消耗而聞名。2011年6月1日,nginx 1.0.4發布。

nginx的特點是占有內存少,并發能力強,事實上nginx的并發能力確實在同類型的網頁服務器中表現較好,中國大陸使用nginx網站用戶有:百度、京東、新浪、網易、騰訊、淘寶等。

二、Nginx工作原理

Nginx默認采用多進程工作方式,Nginx啟動后,會運行一個master進程和多個worker進程。其中master充當整個進程組與用戶的交互接口,同時對進程進行監護,管理worker進程來實現重啟服務、平滑升級、更換日志文件、配置文件實時生效等功能。worker用來處理基本的網絡事件,worker之間是平等的,他們共同競爭來處理來自客戶端的請求。

工作方式
在工作方式上,Nginx分為單工作進程和多工作進程兩種模式。在單工作進程模式下,除主進程外,還有一個工作進程,工作進程是單線程的;在多工作進程模式下,每個工作進程包含多個線程。Nginx默認為單工作進程模式。

Nginx在啟動后,會有一個master進程和多個worker進程。

master進程:管理進程

master進程主要用來管理worker進程,具體包括如下4個主要功能:

  • (1)接收來自外界的信號。
  • (2)向各worker進程發送信號。
  • (3)監控worker進程的運行狀態。
  • (4)當worker進程退出后(異常情況下),會自動重新啟動新的woker進程。

用戶交互接口master進程充當整個進程組與用戶的交互接口,同時對進程進行監護。它不需要處理網絡事件,不負責業務的執行,只會通過管理worker進程來實現重啟服務、平滑升級、更換日志文件、配置文件實時生效等功能。

重啟work進程:我們要控制nginx,只需要通過killmaster進程發送信號就行了。比如kill -HUP pid,則是告訴nginx,從容地重啟nginx,我們一般用這個信號來重啟nginx,或重新加載配置,因為是從容地重啟,因此服務是不中斷的。

master進程在接收到HUP信號后是怎么做的呢?

1)、首先master進程在接到信號后,會先重新加載配置文件,然后再啟動新的worker進程,并向所有老的worker進程發送信號,告訴他們可以光榮退休了。2)、新的worker在啟動后,就開始接收新的請求,而老的worker在收到來自master的信號后,就不再接收新的請求,并且在當前進程中的所有未處理完的請求處理完成后,再退出。

直接給master進程發送信號,這是比較傳統的操作方式,nginx在0.8版本之后,引入了一系列命令行參數,來方便我們管理。比如,./nginx -s reload,就是來重啟nginx,./nginx -s stop,就是來停止nginx的運行。如何做到的呢?我們還是拿reload來說,我們看到,執行命令時,我們是啟動一個新的nginx進程,而新的nginx進程在解析到reload參數后,就知道我們的目的是控制nginx來重新加載配置文件了,它會向master進程發送信號,然后接下來的動作,就和我們直接向master進程發送信號一樣了。

worker進程:處理請求

而基本的網絡事件,則是放在worker進程中來處理了。多個worker進程之間是對等的,他們同等競爭來自客戶端的請求,各進程互相之間是獨立的。一個請求,只可能在一個worker進程中處理,一個worker進程,不可能處理其它進程的請求。worker進程的個數是可以設置的,一般我們會設置與機器cpu核數一致,這里面的原因與nginx的進程模型以及事件處理模型是分不開的。

worker進程之間是平等的,每個進程,處理請求的機會也是一樣的。當我們提供80端口的http服務時,一個連接請求過來,每個進程都有可能處理這個連接,怎么做到的呢?

Nginx采用異步非阻塞的方式來處理網絡事件,類似于Libevent,具體過程如下:

1)接收請求:首先,每個worker進程都是從master進程fork過來,在master進程建立好需要listen的socket(listenfd)之后,然后再fork出多個worker進程。所有worker進程的listenfd會在新連接到來時變得可讀,每個work進程都可以去accept這個socket(listenfd)。當一個client連接到來時,所有accept的work進程都會受到通知,但只有一個進程可以accept成功,其它的則會accept失敗。為保證只有一個進程處理該連接,Nginx提供了一把共享鎖accept_mutex來保證同一時刻只有一個work進程在accept連接。所有worker進程在注冊listenfd讀事件前搶accept_mutex,搶到互斥鎖的那個進程注冊listenfd讀事件,在讀事件里調用accept接受該連接。2)處理請求:當一個worker進程在accept這個連接之后,就開始讀取請求,解析請求,處理請求,產生數據后,再返回給客戶端,最后才斷開連接,這樣一個完整的請求就是這樣的了。

我們可以看到,一個請求,完全由worker進程來處理,而且只在一個worker進程中處理。worker進程之間是平等的,每個進程,處理請求的機會也是一樣的。

三、nginx的安裝

//創建系統用戶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++ 安裝過程略.... [root@localhost ~]# yum -y groups mark install 'Development Tools' Loaded plugins: product-id, search-disabled-repos, subscription-manager This system is not registered with an entitlement server. You can use subscription-manager to register. There is no installed groups file. Maybe run: yum groups mark convert (see man yum) Marked 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 安裝過程略....

nginx安裝后配置

//配置環境變量 [root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh [root@localhost ~]# . /etc/profile.d/nginx.sh//服務控制方式,使用nginx命令-t //檢查配置文件語法-v //輸出nginx的版本-c //指定配置文件的路徑-s //發送服務控制信號,可選值有{stop|quit|reopen|reload}//啟動nginx [root@localhost ~]# nginx [root@localhost ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 *:80 *:* LISTEN 0 128 *:22 *:* LISTEN 0 100 127.0.0.1:25 *:* LISTEN 0 128 :::22 :::* LISTEN 0 100 ::1:25 :::*

四、nginx的配置文件詳解

主配置文件:/usr/local/nginx/conf/nginx.conf

  • 默認啟動nginx時,使用的配置文件是:安裝路徑/conf/nginx.conf文件
  • 可以在啟動nginx時通過-c選項來指定要讀取的配置文件

nginx常見的配置文件及其作用

配置文件作用
nginx.confnginx的基本配置文件
mime.typesMIME類型關聯的擴展文件
fastcgi.conf與fastcgi相關的配置
proxy.conf與proxy相關的配置
sites.conf配置nginx提供的網站,包括虛擬主機

nginx.conf配置詳解
nginx.conf的內容分為以下幾段:

  • main配置段:全局配置段。其中main配置段中可能包含event配置段
  • event {}:定義event模型工作特性
  • http {}:定義http協議相關的配置
    配置指令:要以分號結尾,語法格式如下:
derective value1 [value2 ...];

支持使用變量:

  • 內置變量:模塊會提供內建變量定義
  • 自定義變量:set var_name value

用于調試、定位問題的配置參數

daemon {on|off}; //是否以守護進程方式運行nginx,調試時應設置為off master_process {on|off}; //是否以master/worker模型來運行nginx,調試時可以設置為off error_log 位置 級別; //配置錯誤日志

error_log里的位置和級別能有以下可選項:

位置級別
file; stderrl syslog:server=address[,parameter=value] ; memory:sizedebug:若要使用debug級別,需要在編譯nginx時使用–with-debug選項 ;info ;notice ;warn ;erro ;crit ;alert ;emerg

1. 正常運行必備的配置參數

user USERNAME [GROUPNAME]; 指定運行worker進程的用戶和組

用法 Syntax: user user [group]; #語法 Default: user nobody nobody; #默認值 Context: main #可以配置在那個字段中[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf user nginx; #建議手動指定用戶 worker_processes 1;

pid /path/to/pid_file; 指定nginx守護進程的pid文件

用法 Syntax: pid file; Default: pid logs/nginx.pid; Context: main[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf user nginx; worker_processes 1; error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info;pid logs/nginx.pid;

worker_rlimit_nofile number; 設置所有worker進程最大可以打開的文件數,默認為1024

用法 Syntax: worker_rlimit_nofile number; Default: 1024 Context: main

worker_rlimit_core size; 指明所有worker進程所能夠使用的總體的最大核心文件大小,保持默認即可

用法 Syntax: worker_rlimit_core size; Default: — Context: main

2.優化性能的配置參數

worker_processes n; 啟動n個worker進程,這里的n為了避免上下文切換,通常設置為cpu總核心數-1或等于總核心數

用法 Syntax: worker_processes number | auto; Default: worker_processes 1; Context: main[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf #user nobody; worker_processes 4; //修改nginx的worker進程數量,默認為1[root@nginx ~]# nginx -s reload //發送服務控制信號,重新加載配置文件 [root@nginx ~]# ps -ef | grep nginx root 4980 1 0 19:22 ? 00:00:00 nginx: master process nginx nginx 5202 4980 0 19:22 ? 00:00:00 nginx: worker process nginx 5203 4980 0 19:22 ? 00:00:00 nginx: worker process nginx 5204 4980 0 19:22 ? 00:00:00 nginx: worker process nginx 5205 4980 0 19:22 ? 00:00:00 nginx: worker process root 5564 3373 0 19:22 pts/0 00:00:00 grep --color=auto nginx 注: worker_processes的數量*worker_connections的數量=nginx所能支持的最大并發連接數量,在實際情況最大并發數建議不超過30000

worker_cpu_affinity cpumask …; 將進程綁定到某cpu中,避免頻繁刷新緩存

用法 Syntax: worker_cpu_affinity cpumask ...;worker_cpu_affinity auto [cpumask]; Default: — Context: main 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核心特殊值 (1.9.10) 允許將工作進程自動綁定到可用的 CPU:auto worker_processes auto; worker_cpu_affinity auto; 可選掩碼參數可用于限制可用于自動綁定的 CPU: worker_cpu_affinity auto 01010101; 該指令僅在 FreeBSD 和 Linux 上可用。[root@nginx ~]# nproc #查看cpu的核心數 4 [root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf #user nobody; worker_processes 3 ; worker_cpu_affinity 0001 0010 0100; #將進程綁定在0,1,2cpu核心上運行[root@nginx ~]# ps -ef | grep nginx root 4980 1 0 19:22 ? 00:00:00 nginx: master process nginx nginx 29238 4980 0 19:36 ? 00:00:00 nginx: worker process nginx 29239 4980 0 19:36 ? 00:00:00 nginx: worker process nginx 29240 4980 0 19:36 ? 00:00:00 nginx: worker process root 29290 3373 0 19:36 pts/0 00:00:00 grep --color=auto nginx

查看進程綁定的cpu是哪一個

timer_resolution interval; 計時器解析度。降低此值,可減少gettimeofday()系統調用的次數

用法 Syntax: timer_resolution interval; Default: — Context: main

worker_priority number; 指明worker進程的nice值

用法 Syntax: worker_priority number; Default: worker_priority 0; Context: main[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf #user nobody; worker_processes 3 ; worker_cpu_affinity 0001 0010 0100; worker_priority -20;[root@nginx ~]# nginx -s reload [root@nginx ~]# ps -elf | grep nginx 1 S root 4980 1 0 80 0 - 20116 - 19:22 ? 00:00:00 nginx: master process nginx 5 S nginx 50563 4980 0 60 -20 - 27944 do_epo 19:47 ? 00:00:00 nginx: worker process 5 S nginx 50564 4980 0 60 -20 - 27944 do_epo 19:47 ? 00:00:00 nginx: worker process 5 S nginx 50565 4980 0 60 -20 - 27944 do_epo 19:47 ? 00:00:00 nginx: worker process 0 S root 50900 3373 0 80 0 - 3086 - 19:47 pts/0 00:00:00 grep --color=auto nginx

3.事件相關的配置:event{}段中的配置參數

accept_mutex {off|on}; master 調度用戶請求至各worker進程時使用的負載均衡鎖;on表示能讓多個worker輪流地、序列化地去響應新請求

用法 Syntax: accept_mutex on | off; Default: accept_mutex off; Context: events

lock_file file; accept_mutex 用到的互斥鎖鎖文件路徑

用法 Syntax: lock_file file; Default: lock_file logs/nginx.lock; Context: main

use [epoll | rtsig | select | poll]; 指明使用的事件模型,建議讓nginx自行選擇

用法 Syntax: use method; Default: — Context: events

worker_connections #; 每個進程能夠接受的最大連接數

用法 Syntax: worker_connections number; Default: worker_connections 512; Context: events[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf #user nobody; worker_processes 3 ; worker_cpu_affinity 0001 0010 0100; worker_priority -20;#error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info;#pid logs/nginx.pid;events {worker_connections 20480; #最大連接數乘以進程數量除以2就是最大訪問并發量3000 }

4.網絡連接相關的配置參數

keepalive_timeout number; 長連接的超時時長,默認為65s

用法 Syntax: keepalive_timeout timeout [header_timeout]; Default: keepalive_timeout 65s; Context: http, server, location[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf .... http {include 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"';#access_log logs/access.log main;sendfile on;#tcp_nopush on;keepalive_timeout 65; ....

keepalive_requests number; 在一個長連接上所能夠允許請求的最大資源數

用法 Syntax: keepalive_requests number; Default: keepalive_requests 1000; Context: http, server, location.... http {include 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"';#access_log logs/access.log main;sendfile on;#tcp_nopush on;keepalive_timeout 65;keepalive_requests 1000;

keepalive_disable [msie6|safari|none]; 為指定類型的UserAgent禁用長連接

用法 Syntax: keepalive_disable none | browser ...; Default: keepalive_disable msie6; Context: http,server,location

tcp_nodelay on|off; //是否對長連接使用TCP_NODELAY選項,為了提升用戶體驗,通常設為on

用法 Syntax: tcp_nodelay on | off; Default: tcp_nodelay on; Context: http, server, location

client_header_timeout number; 讀取http請求報文首部的超時時長

用法 Syntax: client_header_timeout time; Default: client_header_timeout 60s; Context: http, server

client_body_timeout number; 讀取http請求報文body部分的超時時長

用法 Syntax: client_body_timeout time; Default: client_body_timeout 60s; Context: http, server,location

send_timeout number; 發送響應報文的超時時長

用法 Syntax: send_timeout time; Default: send_timeout 60s; Context: http, server, location

5.fastcgi的相關配置參數

LNMP:php要啟用fpm模型
配置示例如下:

location ~ \.php$ {root html;fastcgi_pass 127.0.0.1:9000; #定義反向代理,此處的IP地址應該為PHP服務器的地址fastcgi_index index.php;fastcgi_param SCRIPT_FILENAME $DocumentRoot$fastcgi_script_name;include fastcgi_params;}

6.常需要進行調整的參數

worker_processes //進程數量 worker_connections //單個進程能夠打開的連接數的數量 worker_cpu_affinity //cpu核心的綁定 worker_priority //進程的優先級

7.nginx作為web服務器時使用的配置

http{…}段是配置http相關,由ngx_http_core_module模塊引入。nginx的HTTP配置主要包括四個區塊

http { //協議級別include mime.types;default_type application/octet-stream;keepalive_timeout 65;gzip on;upstream { //負載均衡配置...}server { //服務器級別,每個server類似于httpd中的一個<VirtualHost>listen 80;server_name localhost;location / { //請求級別,類似于httpd中的<Location>,用于定義URL與本地文件系統的映射關系root html;index index.html index.htm;}} }

8.http{}段配置指令

server {}:定義一個虛擬主機

......server{listen 8080;server_name www.csl.com;location / {root html/test;index index.html;}}#access_log logs/host.access.log main;location / {root html/test; index index.html index.htm;}#error_page 404 /404.html;......[root@nginx ~]# cd /usr/local/nginx/html/ [root@nginx html]# ls 50x.html index.html [root@nginx html]# mkdir test [root@nginx html]# ls 50x.html index.html test [root@nginx html]# echo 'hello world' > test/index.html[root@nginx html]# nginx -s stop;nginxlisten:指定監聽的地址和端口 listen address[:port]; listen port;server_name NAME [...]; 后面可跟多個主機,名稱可使用正則表達式或通配符,當存在多個server時,匹配順序如下:1. 先做精確匹配檢查 2. 左側通配符匹配檢查,如*.example.com 3. 右側通配符匹配檢查,如web.* 4. 正則表達式匹配檢查,如~ ^.*\.example\.com$ 5. default_server

五、更改默認端口號以及進程數和指定特定配置文件

默認配置文件(/usr/local/nginx/conf/)nginx.conf文件內容**

[root@nginx conf]# pwd /usr/local/nginx/conf [root@nginx conf]# head nginx.conf#user nobody; worker_processes 1;#error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info;#pid logs/nginx.pid; ....... server {listen 80;server_name localhost; 使用默認配置文件運行進程數如下 [root@nginx ~]# nginx [root@nginx ~]# ps -ef |grep nginx root 9519 1 0 16:25 ? 00:00:00 nginx: master process nginx nginx 9520 9519 0 16:25 ? 00:00:00 nginx: worker process root 9666 1614 0 16:25 pts/1 00:00:00 grep --color=auto nginx

將默認配置文件以及mime.types文件copy一份到/opt目錄中

[root@nginx conf]# cp nginx.conf /opt/ [root@nginx conf]# cp mime.types /opt/ [root@nginx conf]# ll /opt/ 總用量 12 -rw-r--r-- 1 root root 5231 10月 25 16:28 mime.types -rw-r--r-- 1 root root 2656 10月 25 16:28 nginx.conf[root@localhost conf]# nginx -t -c /opt/nginx.conf nginx: the configuration file /opt/nginx.conf syntax is ok nginx: configuration file /opt/nginx.conf test is successful設置所有worker進程最大可以打開的文件數 #user nobody; worker_processes 4; #改為4個進程#error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info;#pid logs/nginx.pid; ....... server {listen 8080; #更改端口號8080server_name localhost;使用nginx服務控制命令重啟并指定配置文件路徑 [root@nginx opt]# nginx -s stop;nginx -c /opt/nginx.conf [root@nginx opt]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 0.0.0.0:111 0.0.0.0:* LISTEN 0 128 0.0.0.0:8080 0.0.0.0:* LISTEN 0 32 192.168.122.1:53 0.0.0.0:* LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 5 127.0.0.1:631 0.0.0.0:* LISTEN 0 128 [::]:111 [::]:* LISTEN 0 128 [::]:22 [::]:* LISTEN 0 5 [::1]:631 [::]:* [root@nginx opt]# ps -ef | grep nginx root 31901 1 0 16:35 ? 00:00:00 nginx: master process nginx -c /opt/nginx.conf nginx 31902 31901 0 16:35 ? 00:00:00 nginx: worker process nginx 31903 31901 0 16:35 ? 00:00:00 nginx: worker process nginx 31904 31901 0 16:35 ? 00:00:00 nginx: worker process nginx 31905 31901 0 16:35 ? 00:00:00 nginx: worker process root 33427 1614 0 16:36 pts/1 00:00:00 grep --color=auto nginx

訪問測試

六、訪問控制

注:用于location段,可以用主機地址表示,也可用網段表示,必須一起用
allow:設定允許那臺或那些主機訪問,多個參數間用空格隔開
deny:設定禁止那臺或那些主機訪問,多個參數間用空格隔開

allow 192.168.1.1/32 ; allow 192.168.2.1/32 ; deny all;

配置訪問規則

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf......location / {root html;index index.php index.html index.htm;allow 192.168.153.159/32; #允許訪問deny all; #配置拒絕所有訪問} ...... [root@nginx ~]# systemctl restart nginx [root@nginx ~]# ss -anlt State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 0.0.0.0:8080 0.0.0.0:* LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 128 *:80 *:* LISTEN 0 128 [::]:22 [::]:*

訪問測試
本機訪問

使用另一臺主機訪問

[root@localhost ~]# curl 192.168.153.139 hello world

七、配置錯誤頁面

配置自定義錯誤頁面

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf ...... error_page 404 /404.html; #找到此行取消注釋 ......[root@nginx ~]# vim /usr/local/nginx/html/404.html #創建自定義錯誤頁面 this is a error page[root@nginx ~]# nginx -s reload # 重啟服務

輸入一個不存在的網頁頁面測試

配置錯誤頁面響應狀態碼

error_page code […] [=code] URI | @name 根據http響應狀態碼來指明特用的錯誤頁面,例如

error_page 404 /404.html

[=code]:以指定的響應碼進行響應,而不是默認的原來的響應,默認表示以新資源的響應碼為其響應碼,例如

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf ......error_page 404 =200 /404.html ......

八、日志

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; #訪問日志//log_format中每一段的含義 remote_addr:對應客戶端的地址 remote_user:是請求客戶端請求認證的用戶名,如果沒有開啟認證模塊的話是值為空。 time_local:表示nginx服務器時間 request:表示request請求頭的行 status:表示response的返回狀態 body_bytes_sent:表示從服務端返回給客戶端的body數據大小 http_referer:表示請求的上一級頁面 http_user_agent:表示agent信息 http_x_forwarded_for:會記錄每一級請求中信息//注意:此處可用變量為nginx各模塊內建變量

示例

[root@nginx ~]# vim /usr/local/nginx/conf/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 logs/access.log main; ......[root@nginx ~]# curl 192.168.153.139 # 訪問測試[root@nginx ~]# tail -f /usr/local/nginx/logs/access.log #查看訪問日志 192.168.153.1 - - [27/Oct/2021:14:30:10 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30" "-"

九、平滑升級

獲取現有的程序編譯的參數

[root@nginx ~]# nginx -V nginx version: nginx/1.20.1 built by gcc 8.4.1 20200928 (Red Hat 8.4.1-1) (GCC) built with OpenSSL 1.1.1g FIPS 21 Apr 2020 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

獲取新版本的軟件包或功能包

下載地址 github.com

[root@nginx ~]# cd /usr/src/ [root@nginx src]# ls debug kernels nginx-1.20.1 echo-nginx-module-master.zip nginx-1.20.1.tar.gz[root@nginx src]# yum -y install unzip [root@nginx src]# unzip echo-nginx-module-master.zip [root@nginx src]# ls debug kernels echo-nginx-module-master nginx-1.20.1 echo-nginx-module-master.zip nginx-1.20.1.tar.gz

將新功能或新版本進行編譯

[root@nginx src]# cd nginx-1.20.1/ [root@nginx nginx-1.20.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=../echo-nginx-module-master [root@nginx nginx-1.20.1]# make

備份原程序

[root@nginx nginx-1.20.1]# ll objs/nginx nginx nginx.8 [root@nginx nginx-1.20.1]# ll objs/nginx /usr/local/nginx/sbin/nginx -rwxr-xr-x. 1 root root 6829960 10月 27 15:09 objs/nginx -rwxr-xr-x. 1 root root 6307576 10月 26 13:02 /usr/local/nginx/sbin/nginx [root@nginx nginx-1.20.1]# cp /usr/local/nginx/sbin/nginx /opt/nginx

替換原程序

[root@nginx nginx-1.20.1]# cp objs/nginx /usr/local/nginx/sbin/nginx

十、locaton配置

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

//功能:允許根據用戶請求的URI來匹配定義的各location,匹配到時,此請求將被相應的location配置塊中的配置所處理,例如做訪問控制等功能//語法:location [ 修飾符 ] pattern {......}

常用修飾符說明:

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

示例

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

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf ......#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location /test { #匹配/test下的所有echo "test";}error_page 404 /404.html;# redirect server error pages to the static page /50x.html......[root@nginx ~]# 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@nginx ~]# nginx -s reload[root@nginx html]# curl http://192.168.153.139 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style>body {width: 35em;margin: 0 auto;font-family: Tahoma, Verdana, Arial, sans-serif;} </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p><p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p><p><em>Thank you for using nginx.</em></p> </body> </html> [root@nginx html]# [root@nginx html]# curl http://192.168.153.139/test test

精確匹配

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf ......#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location /test { #匹配/test下的所有echo "test";}location = /test {echo "example";}error_page 404 /404.html;# redirect server error pages to the static page /50x.html......[root@nginx ~]# 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@nginx conf]# nginx -s reload測試 [root@nginx html]# curl http://192.168.153.139/test example [root@nginx html]# curl http://192.168.153.139/test/ test [root@nginx html]# curl http://192.168.153.139/test/hh test

十一、用戶驗證

#安裝httpd-tools [root@master ~]# yum -y install httpd-tools#確保用戶不存在 [root@master ~]# id chen id: “chen”:無此用戶#生成用戶認證文件 [root@master ~]# htpasswd -c -m /usr/local/nginx/conf/.user-auth-file chen New password: Re-type new password: Adding password for user chen [root@master ~]# cat /usr/local/nginx/conf/.user-auth-file chen:$apr1$ndGn.GPK$2sSpQbZwt4H0UeeMsbsm4/#創建測試文件 [root@master ~]# mkdir -p /usr/local/nginx/html/chen [root@master ~]# echo "hello chen" > /usr/local/nginx/html/chen/index.html [root@master ~]# vim /usr/local/nginx/conf/nginx.conf ......#access_log logs/host.access.log main;location /chen {root html;index index.html index.htm;auth_basic "chen"; #添加此行auth_basic_user_file "/usr/local/nginx/conf/.user-auth-file"; #添加此行}#error_page 404 /404.html;# redirect server error pages to the static page /50x.html......[root@nginx ~]# 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@nginx ~]# nginx -s reload

瀏覽器訪問測試

十二、https配置

#創建證書存放目錄 [root@nginx ~]# mkdir -p /etc/nginx/ssl [root@nginx ~]# cd /etc/nginx/ssl/ #生成密鑰 [root@nginx ssl]# openssl genrsa -out example.key 2048 Generating RSA private key, 2048 bit long modulus (2 primes) .................................................................+++++ .....................................+++++ e is 65537 (0x010001) #生成證書 [root@nginx ssl]# openssl req -new -key example.key -out example.csr 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) []:hubei Locality Name (eg, city) [Default City]:wuhan Organization Name (eg, company) [Default Company Ltd]:chen Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) []:csl Email Address []:Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: [root@nginx ssl]# [root@nginx ssl]# ls example.csr example.key [root@nginx ssl]# openssl x509 -req -days 365 -in example.csr -signkey example.key -out example.crt Signature ok subject=C = CN, ST = hubei, L = wuhan, O = chen, CN = csl Getting Private key [root@nginx ssl]# ls example.crt example.csr example.key

修改nginx配置文件

//取消下面列出行的注釋并修改域名和證書位置 [root@master ~]# vim /usr/local/nginx/conf/nginx.conf ······ server {listen 443 ssl;server_name www.csl.com; #更改域名ssl_certificate /etc/nginx/ssl/example.crt; #更改此行ssl_certificate_key /etc/nginx/ssl/example.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;} } ......[root@nginx ~]# nginx -s reload

瀏覽器訪問

十三、狀態頁面配置

開啟狀態頁面功能

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf ......#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location /status {stub_status ;allow 192.168.153.139/32;}#error_page 404 /404.html; ......[root@nginx ~]# 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@nginx ~]# nginx -s reload

訪問狀態頁面的方式:

http://server_ip/status

在瀏覽器中進入狀態頁面

狀態頁面信息詳解:

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

狀態頁面監控

主機名ip職責系統
nginx192.168.153.139nginx zabbix_clientcenos7
zabbix192.168.153.130zabbix_servercenos7

準備工作:

zabbix server端安裝

zabbix 客戶端安裝及配置

配置

修改agent配置文件/usr/local/etc/zabbix_agentd.conf [root@nginx ~]# vim /usr/local/etc/zabbix_agentd.conf UnsafeUserParameters=1 #取消注釋并修改值為1 Server=192.168.153.130 ServerActive=192.168.153.130 #服務端IP Hostname=NGINX啟動服務 [root@nginx ~]# zabbix_agentd [root@nginx ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port Process LISTEN 0 128 0.0.0.0:10050 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 128 0.0.0.0:443 0.0.0.0:* LISTEN 0 128 [::]:22 [::]:* 在agentd編寫腳本 [root@nginx ~]# cd /scripts/ [root@nginx scripts]# cat status.sh #! /bin/bashcase $1 in"Reading")curl -s http://192.168.25.147/status | awk 'NR==4 {print $2}';;"Writing")curl -s http://192.168.25.147/status | awk 'NR==4 {print $4}';;"Waiting")curl -s http://192.168.25.147/status | awk 'NR==4 {print $6}' esac修改/usr/local/etc/zabbix_agentd.conf [root@nginx ~]# vim /usr/local/etc/zabbix_agentd.conf UserParameter=check_status.sh[*],/bin/bash /scripts/status.sh $1重啟agentd端的zabbix服務 [root@nginx ~]# pkill zabbix_agentd [root@nginx ~]# zabbix_agentd 在zabbix服務器上測試key鍵值是否有效 [root@localhost ~]# zabbix_get -s 192.168.153.139 -k check_status[Writing] 1

十四、rewrite配置

rewriet的作用
rewrite模塊即ngx_http_rewrite_module模塊,主要功能是改寫請求URI,是Nginx默認安裝的模塊。rewrite模塊會根據PCRE正則匹配重寫URI,然后發起內部跳轉再匹配location,或者直接做30x重定向返回客戶端。

語法:rewrite regex replacement flag;
說明

rewrite為固定關鍵字,表示開始進行rewrite匹配規則regex部分是 ^/(.*) ,這是一個正則表達式,匹配完整的域名和后面的路徑地址replacement部分是http://www.123.com/$1 $1,是取自regex部分()里的內容。匹配成功后跳轉到的URL。flag部分 permanent表示永久301重定向標記,即跳轉到新的 http://www.123.com/$1 地址上

示例

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

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

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

如上例所示,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)
  • break示例
  • break 本條規則匹配完成即終止,不再匹配后面的任何規則

    [root@nginx ~]# cd /usr/local/nginx/html/ [root@nginx html]# mkdir imgs [root@nginx html]# ls 404.html 50x.html imgs index.html [root@nginx imgs]# ls 1.jpg[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf ......#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location /images {rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;}#error_page 404 /404.html;......[root@nginx ~]# 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@nginx ~]# nginx -s reload

    瀏覽器訪問測試

  • redirect示例
  • redirect 返回302臨時重定向,瀏覽器地址會顯示跳轉后的URL地址

    [root@nginx ~]# cd /usr/local/nginx/html/ [root@nginx html]# mkdir imgs [root@nginx html]# ls 404.html 50x.html imgs index.html [root@nginx imgs]# ls 1.jpg[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf ......#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location /images {rewrite ^/images/(.*\.jpg)$ https://tse1-mm.cn.bing.net/th/id/R-C.81a9c8eacd1f0df67330ef6f4c9a3b19?rik=eJUdnxNkEXT8KQ&riu=http%3a%2f%2fi0.hdslb.com%2fbfs%2farchive%2ff9ae78de05acbce3613128a03706074fe70fc569.jpg&ehk=506IfAtWt2ujZFtzT4KlvNrtxWgZ9wD8rcMCRKQFi14%3d&risl=&pid=ImgRaw&r=0 redirect;}#error_page 404 /404.html;......[root@nginx ~]# 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@nginx ~]# nginx -s reload

    瀏覽器訪問測試

  • last和break組合使用示例
  • last 本條規則匹配完成后,繼續向下匹配新的location URI規則
    break 本條規則匹配完成即終止,不再匹配后面的任何規則

    示例1

    [root@nginx ~]# cd /usr/local/nginx/html/ [root@nginx html]# mkdir imgs [root@nginx html]# ls 404.html 50x.html imgs index.html [root@nginx imgs]# ls 1.jpg[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf ......#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location /images {rewrite ^/images/(.*\.jpg)$ /imgs/$1 last; }location /imgs {rewrite ^/imgs/(.*\.jpg)$ http://images.baidu.com last;}#error_page 404 /404.html;......[root@nginx ~]# 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@nginx ~]# nginx -s reload

    瀏覽器訪問
    發現訪問到第二條規則的頁面

    示例2

    [root@nginx ~]# cd /usr/local/nginx/html/ [root@nginx html]# mkdir imgs [root@nginx html]# ls 404.html 50x.html imgs index.html [root@nginx imgs]# ls 1.jpg[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf ......#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location /images {rewrite ^/images/(.*\.jpg)$ /imgs/$1 break; }location /imgs {rewrite ^/imgs/(.*\.jpg)$ http://images.baidu.com last;}#error_page 404 /404.html;......[root@nginx ~]# 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@nginx ~]# nginx -s reload

    瀏覽器訪問
    發現訪問到第一條規則的頁面

    十五、if用法

    語法:if (condition) {…}

    應用場景:

    • server段
    • location段

    常見的condition

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

    基于瀏覽器實現分離案例

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

    防盜鏈案例

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

    十六、反向代理與負載均衡

    • nginx通常被用作后端服務器的反向代理,這樣就可以很方便的實現動靜分離以及負載均衡,從而大大提高服務器的處理能力
    • nginx實現動靜分離,其實就是在反向代理的時候,如果是靜態資源,就直接從nginx發布的路徑去讀取,而不需要從后臺服務器獲取了
    • 但是要注意,這種情況下需要保證后端跟前端的程序保持一致,可以使用Rsync做服務端自動同步或者使用NFS、MFS分布式共享存儲
    • Http Proxy模塊,功能很多,最常用的是proxy_pass和proxy_cache
    • 如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模塊,用來清除指定的URL緩存。這個集成需要在安裝nginx的時候去做,如:./configure --add-module=…/ngx_cache_purge-1.0 …
    • nginx通過upstream模塊來實現簡單的負載均衡,upstream需要定義在http段內在upstream段內,定義一個服務器列表,默認的方式是輪詢,如果要確定同一個訪問者發出的請求總是由同一個后端服務器來處理,可以設置ip_hash

    環境

    主機名IP服務
    nginx192.168.153.142nginx
    agent192.168.153.153nginx
    httpd192.168.153.139httpd

    注:nginx服務都是源碼安裝 、httpd為yum安裝
    準備工作
    每臺主機開啟服務,并關閉防火墻略

    部署nginx 創建系統用戶nginx[root@agent ~]# useradd -r -M -s /sbin/nologin nginx 安裝依賴環境[root@agent ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ 安裝過程略.... [root@agent ~]# yum -y groups mark install 'Development Tools' Loaded plugins: product-id, search-disabled-repos, subscription-manager This system is not registered with an entitlement server. You can use subscription-manager to register. There is no installed groups file. Maybe run: yum groups mark convert (see man yum) Marked install: Development Tools 創建日志存放目錄[root@agent ~]# mkdir -p /var/log/nginx [root@agent ~]# chown -R nginx.nginx /var/log/nginx 下載nginx[root@agent ~]# cd /usr/src/ [root@agent src]# wget http://nginx.org/download/nginx-1.20.1.tar.gz 預編譯[root@agent src]# ls debug kernels nginx-1.20.1.tar.gz [root@agent src]# tar xf nginx-1.20.1.tar.gz [root@agent src]# cd nginx-1.20.1 [root@agent nginx-1.20.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 編譯安裝[root@agent nginx-1.20.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install 配置環境變量[root@agent ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh [root@agent ~]# . /etc/profile.d/nginx.sh [root@agent ~]# nginx [root@agent ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 *:80 *:* LISTEN 0 128 *:22 *:* LISTEN 0 100 127.0.0.1:25 *:* LISTEN 0 128 :::22 :::* LISTEN 0 100 ::1:25 :::*

    修改配置

    [root@agent ~]# vim /usr/local/nginx/conf/nginx.conf ......#gzip on;upstream test { #配置負載均衡server 192.168.153.139;server 192.168.153.142;}server {listen 80;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / { #配置反向代理proxy_pass http://test;}#error_page 404 /404.html;......[root@agent ~]# 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@agent ~]# nginx -s reload

    使用agent主機IP地址訪問,并刷新測試

    十七、動靜分離

    何為動靜分離呢?
    Nginx 動靜分離,簡單來說,就是動態請求和靜態請求分開,也可以理解成使用 Nginx處理靜態頁面,Tomcat 處理動態頁面。動靜分離從目前實現角度來講大致分為兩種。

    第一種:純粹把靜態文件獨立成單獨的域名,放在獨立的服務器上(主流推崇的方案);
    第二種:動態跟靜態文件混合在一起發布,通過 nginx 來分開。

    通過 location 指定不同的后綴名實現不同的請求轉發,也可以通過 expires 參數設置,使瀏覽器緩存文件的過期時間,從而減少與服務器之前的請求和流量。

    Expires 具體含義:給一個資源設定一個過期時間,也就是說無需去服務端驗證,直接通過瀏覽器自身確認是否過期即可,所以不會產生額外的流量,也就是所謂的客戶端緩存。此種方法非常適合不經常變動的資源。(如果經常更新的文件,不建議使用 Expires 來緩存),假設一下,我們把這個Expires設置 3d,表示在 3 天之內訪問這個 URL,發送一個請求,比對服務器該文件最后更新時間沒有變化,則不會從服務器抓取,返回狀態碼304,如果有修改,則直接從服務器重新下載,返回狀態碼 200。

    我們先來了解一下,使用動靜分離的目的是什么呢?

    為了加快網站的解析速度,我們可以把動態頁面和靜態頁面交給不同的服務器來解析,來加快解析速度,提高請求的訪問效率,降低原來單個服務器的壓力。

    配置動靜分離
    環境

    主機名IP服務
    lnmp192.168.153.142lnmp架構
    agent192.168.153.153nginx
    httpd192.168.153.139httpd

    準備工作
    lnmp主機部署lnmp架構

    創建系統用戶nginx[root@lnmp ~]# useradd -r -M -s /sbin/nologin nginx 安裝依賴環境[root@lnmp ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ 安裝過程略.... [root@lnmp ~]# yum -y groups mark install 'Development Tools' Loaded plugins: product-id, search-disabled-repos, subscription-manager This system is not registered with an entitlement server. You can use subscription-manager to register. There is no installed groups file. Maybe run: yum groups mark convert (see man yum) Marked install: Development Tools 創建日志存放目錄[root@lnmp ~]# mkdir -p /var/log/nginx [root@lnmp ~]# chown -R nginx.nginx /var/log/nginx 下載nginx[root@lnmp ~]# cd /usr/src/ [root@lnmp src]# wget http://nginx.org/download/nginx-1.20.1.tar.gz 預編譯[root@lnmp src]# ls debug kernels nginx-1.20.1.tar.gz [root@lnmp src]# tar xf nginx-1.20.1.tar.gz [root@lnmp src]# cd nginx-1.20.1 [root@lnmp nginx-1.20.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 編譯安裝[root@lnmp nginx-1.20.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install 配置環境變量[root@lnmp ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh [root@lnmp ~]# . /etc/profile.d/nginx.sh 服務控制方式,使用nginx命令-t //檢查配置文件語法-v //輸出nginx的版本-c //指定配置文件的路徑-s //發送服務控制信號,可選值有{stop|quit|reopen|reload} 啟動nginx[root@lnmp ~]# nginx [root@lnmp ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 *:80 *:* LISTEN 0 128 *:22 *:* LISTEN 0 100 127.0.0.1:25 *:* LISTEN 0 128 :::22 :::* LISTEN 0 100 ::1:25 :::* 安裝mysql 安裝依賴包[root@lnmp ~]# yum -y install ncurses-devel openssl-devel openssl cmake mariadb-devel ncurses-compat-libs 創建用戶和組[root@lnmp src]# groupadd -r mysql [root@lnmp src]# useradd -r -M -s /sbin/nologin mysql mysql 下載二進制格式的mysql軟件包[root@lnmp ~]# cd /usr/src/ [root@lnmp src]# wget http://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz 解壓軟件至/usr/local/#解壓 [root@lnmp src]# ls debug kernels mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz [root@lnmp src]# tar xf mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz -C /usr/local/ [root@lnmp ~]# ls /usr/local/ bin games lib libexec sbin src etc include lib64 mysql-5.7.35-linux-glibc2.12-x86_64 share #軟連接 [root@lnmp ~]# cd /usr/local/ [root@lnmp local]# ln -sv mysql-5.7.35-linux-glibc2.12-x86_64/ mysql 'mysql' -> 'mysql-5.7.35-linux-glibc2.12-x86_64/' [root@lnmp local]# ll 總用量 0 drwxr-xr-x. 2 root root 6 8月 12 2018 bin drwxr-xr-x. 2 root root 6 8月 12 2018 etc drwxr-xr-x. 2 root root 6 8月 12 2018 games drwxr-xr-x. 2 root root 6 8月 12 2018 include drwxr-xr-x. 2 root root 6 8月 12 2018 lib drwxr-xr-x. 2 root root 6 8月 12 2018 lib64 drwxr-xr-x. 2 root root 6 8月 12 2018 libexec lrwxrwxrwx. 1 root root 36 9月 23 16:39 mysql -> mysql-5.7.35-linux-glibc2.12-x86_64/ drwxr-xr-x. 9 mysql mysql 129 9月 23 16:38 mysql-5.7.35-linux-glibc2.12-x86_64 drwxr-xr-x. 2 root root 6 8月 12 2018 sbin drwxr-xr-x. 5 root root 49 7月 18 10:33 share drwxr-xr-x. 2 root root 6 8月 12 2018 src修改目錄/usr/local/mysql的屬主屬組[root@lnmp ~]# chown -R mysql.mysql /usr/local/mysql [root@lnmp ~]# ll /usr/local/mysql -d lrwxrwxrwx. 1 mysql mysql 36 9月 23 16:39 /usr/local/mysql -> mysql-5.7.35-linux-glibc2.12-x86_64/添加環境變量[root@lnmp ~]# ls /usr/local/mysql bin docs include lib LICENSE man README share support-files [root@lnmp ~]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh [root@lnmp ~]# . /etc/profile.d/mysql.sh [root@lnmp ~]# echo $PATH /usr/local/mysql/bin:/usr/local/nginx/sbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin 創建數據存放目錄[root@lnmp ~]# mkdir -p /opt/data [root@lnmp ~]# chown -R mysql.mysql /opt/data/ [root@lnmp ~]# ll /opt/ 總用量 0 drwxr-xr-x. 2 mysql mysql 6 9月 23 16:46 data初始化數據庫#請注意這種方法初始化完成后是沒有密碼的 [root@lnmp ~]# /usr/local/mysql/bin/mysqld --initialize-insecure --user=mysql --datadir=/opt/data/ 2021-09-23T08:48:41.261781Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). 2021-09-23T08:48:41.438873Z 0 [Warning] InnoDB: New log files created, LSN=45790 2021-09-23T08:48:41.459162Z 0 [Warning] InnoDB: Creating foreign key constraint system tables. 2021-09-23T08:48:41.527098Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 0d70e7f6-1c4b-11ec-a20e-000c2984a301. 2021-09-23T08:48:41.528205Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened. 2021-09-23T08:48:42.036191Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher. 2021-09-23T08:48:42.036204Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher. 2021-09-23T08:48:42.036605Z 0 [Warning] CA certificate ca.pem is self signed. 2021-09-23T08:48:42.238241Z 1 [Warning] root@lnmp is created with an empty password ! Please consider switching off the --initialize-insecure option. 配置mysql[root@lnmp ~]# ln -sv /usr/local/mysql/include/ /usr/local/include/mysql ‘/usr/local/include/mysql’ -> ‘/usr/local/mysql/include/’ [root@lnmp ~]# echo '/usr/local/mysql/lib' > /etc/ld.so.conf.d/mysql.conf [root@lnmp ~]# ldconfig 生成配置文件[root@lnmp ~]# cat > /etc/my.cnf <<EOF [mysqld] basedir = /usr/local/mysql datadir = /opt/data socket = /tmp/mysql.sock port = 3306 pid-file = /opt/data/mysql.pid user = mysql skip-name-resolve EOF 配置service服務啟動文件[root@lnmp ~]# sed -ri 's#^(basedir=).*#\1/usr/local/mysql#g' /usr/local/mysql/support-files/mysql.server [root@lnmp ~]# sed -ri 's#^(datadir=).*#\1/opt/data#g' /usr/local/mysql/support-files/mysql.server[root@lnmp ~]# vim /usr/lib/systemd/system/mysqld.service [Unit] Description=Mysqld server daemon After=network.target[Service] Type=forking ExecStart=/usr/local/mysql/support-files/mysql.server start ExecStop=/usr/local/mysql/support-files/mysql.server stop[Install] WantedBy=multi-user.target#重新加載 [root@lnmp ~]# systemctl daemon-reload#啟動mysql [root@lnmp ~]# systemctl start mysqld [root@lnmp ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 80 *:3306 *:* LISTEN 0 128 [::]:22 [::]:* 修改密碼#登錄 [root@lnmp ~]# mysql -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.7.35 MySQL Community Server (GPL)Copyright (c) 2000, 2021, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> #設置新密碼 mysql> set password = password('123'); Query OK, 0 rows affected, 1 warning (0.00 sec)mysql> quit Bye安裝php 安裝依賴包[root@lnmp ~]# 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 php-mysqlnd libzip-devel libsqlite3x libsqlite3x-devel oniguruma libzip-devel https://repo.almalinux.org/almalinux/8/PowerTools/x86_64/os/Packages/oniguruma-devel-6.8.2-2.el8.x86_64.rpm 安裝過程略.... 下載php軟件包[root@lnmp ~]# cd /usr/src/ [root@lnmp src]# wget https://www.php.net/distributions/php-8.0.10.tar.gz 下載過程略.... [root@lnmp ~]# tar -xvf php-8.0.10.tar.gz 編譯[root@lnmp ~]# cd /usr/src/php-8.0.10 [root@lnmp 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@lnmp php-8.0.10]# make install 配置環境變量[root@lnmp ~]# echo 'export PATH=/usr/local/php8/bin:$PATH' > /etc/profile.d/php.sh [root@lnmp ~]# source /etc/profile.d/php.sh 生成配置文件[root@lnmp ~]# cd /usr/src/php-8.0.10 [root@lnmp php-8.0.10]# cp php.ini-production /etc/php.ini [root@lnmp php-8.0.10]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm [root@lnmp ~]# chmod +x /etc/rc.d/init.d/php-fpm [root@lnmp ~]# cd /usr/local/php8/etc/ [root@lnmp etc]# cp php-fpm.conf.default php-fpm.conf [root@lnmp etc]# cd php-fpm.d/ [root@lnmp php-fpm.d]# cp www.conf.default www.conf 配置service文件[root@lnmp ~]# vim /usr/lib/systemd/system/php-fpm.service [Unit] Description=Php-fpm server daemon After=network.target[Service] Type=forking ExecStart=service php-fpm start ExecStop=service php-fpm stop[Install] WantedBy=multi-user.target#重新加載 [root@lnmp ~]# systemctl daemon-reload啟動服務[root@lnmp ~]# systemctl start php-fpm.service [root@lnmp ~]# 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:22 0.0.0.0:* LISTEN 0 80 *:3306 *:* LISTEN 0 128 *:80 *:* LISTEN 0 128 [::]:22 [::]:* 創建php訪問界面[root@lnmp ~]# vim /usr/local/nginx/html/index.php <?phpphpinfo(); ?> 修改nginx配置文件[root@lnmp ~]# vim /usr/local/nginx/conf/nginx.conf ......#access_log logs/host.access.log main;location / {root html;index index.html index.php index.htm; #在此行中添加index.php}#error_page 404 /404.html; ......location ~ \.php$ { root html;fastcgi_pass 127.0.0.1:9000;fastcgi_index index.php;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #將/script改為$document_rootinclude fastcgi_params;}重啟服務訪問[root@lnmp ~]# nginx -s reload

    開啟服務

    //httpd主機 [root@httpd ~]# systemctl start httpd [root@httpd ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 0.0.0.0:111 0.0.0.0:* LISTEN 0 32 192.168.122.1:53 0.0.0.0:* LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 5 127.0.0.1:631 0.0.0.0:* LISTEN 0 128 [::]:111 [::]:* LISTEN 0 128 *:80 *:* LISTEN 0 128 [::]:22 [::]:* LISTEN 0 5 [::1]:631 [::]:* //nginx主機 [root@lnmp ~]# nginx [root@lnmp ~]# systemctl start php-fpm.service [root@lnmp ~]# systemctl start mysqld.service [root@lnmp ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 32 192.168.122.1:53 0.0.0.0:* LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 5 127.0.0.1:631 0.0.0.0:* LISTEN 0 128 127.0.0.1:9000 0.0.0.0:* LISTEN 0 128 0.0.0.0:111 0.0.0.0:* LISTEN 0 128 0.0.0.0:80 0.0.0.0:* LISTEN 0 128 [::]:22 [::]:* LISTEN 0 5 [::1]:631 [::]:* LISTEN 0 80 *:3306 *:* LISTEN 0 128 [::]:111 [::]:* //agent主機 [root@agent ~]# nginx [root@agent ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 0.0.0.0:111 0.0.0.0:* LISTEN 0 128 0.0.0.0:80 0.0.0.0:* LISTEN 0 32 192.168.122.1:53 0.0.0.0:* LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 5 127.0.0.1:631 0.0.0.0:* LISTEN 0 128 [::]:111 [::]:* LISTEN 0 128 [::]:22 [::]:* LISTEN 0 5 [::1]:631 [::]:*

    修改agent主機配置文件

    [root@agent ~]# vim /usr/local/nginx/conf/nginx.conf ......#gzip on;upstream static { server 192.168.153.139;}upstream dynamic { server 192.168.153.142; }server {listen 80;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {proxy_pass http://static; #訪問靜態資源會自動跳轉到進行訪問}#error_page 404 /404.html;# redirect server error pages to the static page /50x.html#error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80location ~ \.php$ {proxy_pass http://dynamic; #訪問動態資源會自動跳轉到進行訪問}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000......[root@agent ~]# 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@agent ~]# [root@agent ~]# nginx -s reload

    使用agent主機IP地址訪問測試
    訪問靜態資源

    訪問動態資源

    總結

    以上是生活随笔為你收集整理的Nginx工作原理的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。