Nginx服務
HTTP介紹
## HTTP協議是Hyper Text Transfer Protocol(超文本傳輸協議)的縮寫,是用于從萬維網(WWW:World Wide Web )服務器傳輸超文本到本地瀏覽器的傳送協議。
## HTTP工作在 TCP/IP協議體系中的TCP協議上,是一個基于 TCP/IP 通信協議來傳遞數據(HTML 文件、圖片文件、查詢結果等)。## HTTP 工作原理### HTTP協議工作于客戶端-服務端架構上。瀏覽器作為HTTP客戶端通過URL向HTTP服務端(web服務端)發送的請求報文,這個請求報文包含了請求方法、URL協議版本、請求頭部和請求數據。服務器以一個狀態行作為響應,響應的內容包括協議的版本、成功或錯誤代碼、服務器信息、響應頭部和響應數據。 ### Web服務器有:Nginx,Apache服務器,IIS服務器(Internet Information Services)等。### Web服務器根據接收到的請求后,向客戶端發送響應信息。### HTTP默認端口號為80,但是你也可以改為其他端口。## HTTP 消息結構### HTTP是基于客戶端/服務端(C/S)的架構模型,通過一個可靠的鏈接來交換信息,是一個無狀態的請求/響應協議。### HTTP是無狀態協議,意味著服務器不會保留關于客戶端或請求的任何信息,每個請求都是獨立的,即使是在持久連接(如Keep-Alive)的情況下也是如此。### 一個HTTP"客戶端"是一個應用程序(Web瀏覽器或其他任何客戶端),通過連接到服務器達到向服務器發送一個或多個HTTP的請求的目的。### 一個HTTP"服務器"同樣也是一個應用程序(通常是一個Web服務,如Apache Web服務器或IIS服務器等),通過接收客戶端的請求并向客戶端發送HTTP響應數據。### HTTP使用統一資源標識符(Uniform Resource Identifiers, URI)來傳輸數據和建立連接。## 客戶端請求消息### HTTP 報文可以分為兩類:請求報文(request message)和響應報文(response message),兩者的基本報文結構相同。### 請求報文由請求行、請求頭部和請求體三部分組成。### 請求行由請求方法、請求URI和HTTP版本號組成。 ## 服務器響應消息### 響應報文由狀態行、響應頭部和響應體三部分組成。### 狀態行由HTTP版本號、狀態碼和狀態描述組成。### 響應頭部包含了服務器的信息、日期、內容類型、內容長度等信息。### 響應體是服務器返回給客戶端的實際數據。### 響應體可以是HTML文件、圖片、視頻等任何類型的數據。### 響應頭部和響應體之間用一個空行分隔。## HTTP 請求方法### HTTP協議定義了多種請求方法,最常用的有以下幾種:#### GET:請求指定的頁面信息,并返回實體主體。GET請求只能用來獲取數據,不能用來修改數據。#### POST:向指定資源提交數據進行處理請求(例如,提交表單或上傳文件)。POST請求可能會導致數據的變化。#### PUT:向指定資源位置上傳其最新內容。PUT請求通常用于更新資源。#### DELETE:請求服務器刪除指定的頁面。#### HEAD:類似于GET請求,只不過返回的響應中沒有具體的內容,用于獲取報頭。#### OPTIONS:用于描述目標資源的通信選項。#### TRACE:回顯服務器收到的請求,主要用于測試和診斷。#### CONNECT:HTTP/1.1協議中保留給能夠將連接改為管道方式的代理服務器。#### PATCH:用于對資源進行部分修改。#### 總結 以上請求方法中,GET和POST是最常用的請求方法。其他請求方法如PUT、DELETE、HEAD、OPTIONS、TRACE、CONNECT等在實際應用中使用較少。
## HTTP 響應頭信息### HTTP 響應字段(HTTP Response Headers)是服務器在返回 HTTP 響應時附加的元數據,用于向客戶端(如瀏覽器)傳遞關于響應的附加信息。以下是常見的 HTTP 響應字段及其作用:### 通用字段(General Headers)#### Cache-Control- 用于指定緩存機制的指令。- 例如:`Cache-Control: no-cache`表示不使用緩存。#### Connection- 用于控制是否保持連接的狀態。- 例如:`Connection: keep-alive`表示保持連接。#### Date- 表示響應被生成的日期和時間。- 例如:`Date: Wed, 21 Oct 2015 07:28:00 GMT`。### 響應字段(Response Headers)#### Status- 表示響應的狀態碼和狀態描述。- 例如:`HTTP/1.1 200 OK`表示請求成功。#### Location- 用于重定向時指定新的 URL。- 例如:`Location: http://www.example.com/newpage`。#### Server- 表示服務器的名稱和版本信息。- 例如:`Server: Apache/2.4.1 (Unix)`。#### Set-Cookie- 用于設置 Cookie。- 例如:`Set-Cookie: sessionId=abc123; Path=/; HttpOnly`。#### Retry-After- 用于指示客戶端在多長時間后重試請求。- 例如:`Retry-After: 120`表示在120秒后重試。### 實體字段(Entity Headers)#### Content-Type- 表示響應體的媒體類型。- 例如:`Content-Type: text/html; charset=UTF-8`表示響應體是HTML文檔。#### Content-Length- 表示響應體的長度(以字節為單位)。- 例如:`Content-Length: 348`表示響應體長度為348字節。#### Content-Encoding- 表示響應體的編碼方式。- 例如:`Content-Encoding: gzip`表示響應體經過gzip壓縮。#### Content-Disposition- 用于指示瀏覽器如何處理響應體。- 例如:`Content-Disposition: attachment; filename="file.txt"`表示將響應體作為附件下載,并指定文件名為file.txt。#### Last-Modified- 表示資源最后修改的日期和時間。- 例如:`Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT`。#### ETag- 用于標識資源的版本或狀態。- 例如:`ETag: "abc123"`表示資源的唯一標識符。### 安全相關字段(Security Headers)#### Strict-Transport-Security- 用于指示瀏覽器僅使用 HTTPS 訪問網站。- 例如:`Strict-Transport-Security: max-age=31536000; includeSubDomains`表示在一年內強制使用HTTPS。#### X-Content-Type-Options- 用于防止瀏覽器 MIME 類型嗅探。- 例如:`X-Content-Type-Options: nosniff`表示禁止 MIME 嗅探。#### X-XSS-Protection- 用于啟用或禁用瀏覽器的跨站腳本(XSS)保護。- 例如:`X-XSS-Protection: 1; mode=block`表示啟用 XSS 保護并阻止頁面加載。#### Content-Security-Policy- 用于防止跨站腳本攻擊和數據注入攻擊。- 例如:`Content-Security-Policy: default-src 'self'`表示只允許加載來自同一源的資源。#### X-Frame-Options- 用于防止點擊劫持攻擊。- 例如:`X-Frame-Options: DENY`表示禁止在框架中加載頁面。#### Permissions-Policy- 用于控制瀏覽器功能的訪問權限。- 例如:`Permissions-Policy: geolocation=(self)`表示僅允許同一源訪問地理位置功能。### CORS 相關字段(跨域資源共享)#### Access-Control-Allow-Origin- 用于指定允許訪問資源的源。- 例如:`Access-Control-Allow-Origin: *`表示允許所有源訪問。#### Access-Control-Allow-Methods- 用于指定允許的 HTTP 方法。- 例如:`Access-Control-Allow-Methods: GET, POST`表示允許 GET 和 POST 方法。#### Access-Control-Allow-Headers- 用于指定允許的請求頭部字段。- 例如:`Access-Control-Allow-Headers: Content-Type`表示允許 Content-Type 請求頭部字段。#### Access-Control-Max-Age- 用于指定預檢請求的有效期(以秒為單位)。- 例如:`Access-Control-Max-Age: 3600`表示預檢請求在3600秒內有效。### 其他常用字段#### WWW-Authenticate- 用于指定需要進行身份驗證的方式。- 例如:`WWW-Authenticate: Basic realm="Access to the staging site"`表示使用基本身份驗證。#### Link- 用于指定與當前資源相關的其他資源。- 例如:`Link: <http://example.com>; rel="canonical"`表示當前資源的規范鏈接。
## HTTP 狀態碼### HTTP狀態碼是服務器響應請求時返回的數字代碼,用于表示請求的處理結果。狀態碼分為五類:#### 1xx:信息性狀態碼,表示請求已被接收,繼續處理。#### 2xx:成功狀態碼,表示請求已成功處理。#### 3xx:重定向狀態碼,表示需要進一步操作才能完成請求。#### 4xx:客戶端錯誤狀態碼,表示請求有誤或無法完成。#### 5xx:服務器錯誤狀態碼,表示服務器在處理請求時發生錯誤。### 常見的HTTP狀態碼:#### 200 OK:請求成功,服務器返回所請求的資源。#### 201 Created:請求成功,服務器創建了新的資源。#### 204 No Content:請求成功,但沒有返回任何內容。#### 301 Moved Permanently:請求的資源已被永久移動到新位置。#### 302 Found:請求的資源臨時移動到新位置。#### 304 Not Modified:請求的資源未修改,可以使用緩存的版本。#### 400 Bad Request:請求有誤,服務器無法理解。#### 401 Unauthorized:請求需要身份驗證,未提供或提供的憑據無效。#### 403 Forbidden:服務器拒絕請求,客戶端沒有權限訪問資源。#### 404 Not Found:請求的資源不存在。#### 500 Internal Server Error:服務器內部錯誤,無法完成請求。#### 502 Bad Gateway:作為網關或代理的服務器收到無效響應。### 其他特殊狀態碼#### 418 I'm a teapot:表示服務器是一個茶壺,用于測試和玩笑。#### 429 Too Many Requests:客戶端發送的請求過多,服務器拒絕處理。#### 451 Unavailable For Legal Reasons:由于法律原因,資源不可用。### 常見應用場景#### 301和302:用于URL重定向,301表示永久重定向,302表示臨時重定向。#### 403和404:用于處理權限問題和資源不存在的問題。#### 500和502:用于處理服務器內部錯誤和網關錯誤的問題。
nginx 進階基礎
## nginx 介紹### Nginx是一個高性能的HTTP和反向代理服務器,同時也是一個IMAP/POP3/SMTP代理服務器。### Nginx的設計目標是高性能、高并發、低內存消耗和高穩定性。### Nginx使用事件驅動架構,能夠處理大量并發連接,適合用于高負載的Web應用。### Nginx支持多種操作系統,包括Linux、Windows、Mac OS等。### Nginx的配置文件使用簡單的文本格式,易于閱讀和修改。### Nginx支持模塊化設計,可以根據需要加載不同的模塊來擴展功能。### Nginx可以作為負載均衡器,將請求分發到多個后端服務器,提高系統的可用性和性能。
## 為什么選擇 nginx(優勢)### 高并發,高性能### 高可靠---可以7*24小時不間斷運行### 可擴展性強--模塊化設計,使得添加模塊非常的平穩。### 熱部署--可以在不停止服務器的情況下升級nginx### 反向代理--可以隱藏真實的服務器IP地址### 負載均衡--可以將請求分發到多個后端服務器,提高系統的可用性和性能。### BSD許可證--nginx不止開源免費的我們還可以更具實際需求進行定制修改源代碼### Nginx 安裝非常的簡單,配置文件 非常簡潔(還能夠支持perl語法),Bugs非常少的服務器
## IO多路復用### I/O multiplexing【多并發】#### 第一種方法就是最傳統的多進程并發模型 (每進來一個新的I/O流會分配一個新的線程管理。)#### 第二種方法就是I/O多路復用 (單個線程,通過記錄跟蹤每個I/O流(sock)的狀態,來同時管理多個I/O流 。)### nginx基于事件驅動模型實現I/O多路復用#### 一個請求到來了,nginx使用epoll接收請求的過程是怎樣的?##### 1. nginx主進程創建一個epoll對象##### 2. nginx主進程創建一個監聽socket,并將其添加到epoll對象中##### 3. nginx主進程調用epoll_wait()函數,等待事件的發生##### 4. 當有新的請求到來時,epoll_wait()函數返回,nginx主進程會將新的請求添加到epoll對象中##### 5. nginx主進程會調用worker進程處理請求##### 6. worker進程處理完請求后,將結果返回給客戶端### 異步,非阻塞#### 1個master進程,n個work進程### 為什么更喜歡用Nginx 呢,Nginx 相對Apache 有那些有點呢?#### 輕量級,同樣是web服務比Apache占用更少的內存及資源#### 靜態處理,Nginx 靜態處理性能比 Apache 高 3倍以上#### 抗并發,Nginx 處理請求是異步非阻塞的,而Apache則是阻塞型的。在高并發下Nginx 能保持低資源低消耗高性能。#### 高度模塊化的設計,編寫模塊相對簡單#### 負載均衡,Nginx 支持多種負載均衡算法#### 反向代理,Nginx 支持多種反向代理協議
## nginx安裝部署和配置管理### nginx部署-Yum安裝#### 1.安裝epel源yum install -y epel-release#### 2.安裝nginxyum install -y nginx#### 3.啟動nginxsystemctl start nginx#### 4.設置開機自啟systemctl enable nginx#### 5.查看nginx狀態systemctl status nginx#### 6.查看nginx版本nginx -v### nginx 編譯安裝與配置使用#### 安裝編譯環境yum install -y gcc gcc-c++ pcre pcre-devel gd-devel zlib zlib-devel openssl openssl-devel make### 安裝nginxwget http://nginx.org/download/nginx-1.20.1.tar.gztar -zxvf nginx-1.20.1.tar.gzcd nginx-1.20.1./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-pcre --with-http_stub_status_module --with-http_gzip_static_modulemake && make install### Nginx 編譯參數#### --prefix=/usr/local/nginx //指向安裝目錄#### --conf-path=/etc/nginx/nginx.conf //指定配置文件#### --http-log-path=/var/log/nginx/access.log //指定訪問日志#### --error-log-path=/var/log/nginx/error.log //指定錯誤日志#### --pid-path=/var/run/nginx.pid //指定pid文件#### --http-client-body-temp-path=/var/lib/nginx/body //設定http客戶端請求臨時文件路徑#### --http-fastcgi-temp-path=/var/lib/nginx/fastcgi //設定http fastcgi臨時文件路徑#### --http-proxy-temp-path=/var/lib/nginx/proxy //設定http代理臨時文件路徑#### --http-uwsgi-temp-path=/var/lib/nginx/uwsgi //設定http uwsgi臨時文件路徑#### --http-scgi-temp-path=/var/lib/nginx/scgi //設定http scgi臨時文件路徑#### --with-debug //啟用debug日志#### --with-ipv6 //啟用ipv6支持#### --with-http_ssl_module //啟用ssl模塊#### --with-http_stub_status_module //獲取nginx自上次啟動以來的狀態#### --with-http_realip_module //允許從請求標頭更改客戶端的IP地址值,默認為關#### --with-http_auth_request_module //實現基于一個子請求的結果的客戶端授權。如果該子請求返回的#### --with-http_addition_module //作為一個輸出過濾器,支持不完全緩沖,分部分響應請求#### --with-http_dav_module //支持WebDAV協議#### --with-http_geoip_module //使用預編譯的MaxMind數據庫解析客戶端IP地址,得到變量值#### --with-http_gunzip_module //解壓縮gzip響應#### --with-http_gzip_static_module //支持gzip靜態文件#### --with-http_spdy_module //SPDY可以縮短網頁的加載時間#### --with-http_sub_module //允許用一些其他文本替換nginx響應中的一些文本#### --with-http_xslt_module //過濾轉換XML請求#### --with-mail //郵件代理模塊#### --with-mail_ssl_module //郵件代理模塊SSL支持##### #--with 表示在編譯過程中需要給nginx添加的模塊##### #--without 表示編譯nginx時默認該模塊是添加進去的當使用這個參數時表示將默認編譯的模塊移除### 修改配置文件/etc/nginx/nginx.conf#### 1.修改nginx.conf配置文件vim /etc/nginx/nginx.conf#### 2.修改nginx.conf配置文件##### 全局參數設置user nobody; //設置nginx進程的用戶和組worker_processes 1; //設置nginx工作進程數,建議設置為CPU核心數error_log /var/log/nginx/error.log; //設置錯誤日志文件路徑pid /var/run/nginx.pid; //設置nginx進程ID文件路徑worker_rlimit_nofile 65535; //設置nginx進程打開的最大文件數events {use epoll; //設置事件驅動模型worker_connections 1024; //設置每個工作進程的最大連接數}##### http 服務相關設置include /etc/nginx/mime.types; //設置MIME類型文件路徑default_type application/octet-stream; //設置默認MIME類型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; //設置訪問日志文件路徑sendfile on; //啟用高效文件傳輸模式(可以設置為off,降低系統負載)keepalive_timeout 65; //設置保持連接的超時時間,單位為秒gzip on; //啟用gzip壓縮gzip_types text/plain application/json; //設置gzip壓縮的MIME類型tcp_nopush on; //啟用TCP_NOPUSH選項##### 虛擬服務器的相關設置 server {listen 80; //監聽80端口server_name localhost; //設置服務器名稱location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}server {listen 443 ssl; //監聽443端口,啟用SSLserver_name localhost; //設置服務器名稱ssl_certificate /etc/nginx/ssl/nginx.crt; //設置SSL證書路徑ssl_certificate_key /etc/nginx/ssl/nginx.key; //設置SSL證書密鑰路徑location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}server {listen 8080; //監聽8080端口server_name localhost; //設置服務器名稱location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}### 檢測nginx配置文件是否正確#### yum安裝nginx -t#### 編譯安裝/usr/local/nginx/sbin/nginx -t### 啟動nginx#### yum安裝systemctl start nginx#### 編譯安裝/usr/local/nginx/sbin/nginx### 通過 nginx 命令控制 nginx 服務#### yum安裝命令控制參數nginx -s reload //重新加載配置文件nginx -s reopen //重新打開日志文件nginx -s stop //停止nginx服務nginx -s quit //優雅停止nginx服務nginx -c /path/nginx.conf //指定配置文件路徑nginx -t -c /path/to/nginx.conf //測試配置文件#### 編譯安裝命令控制參數/usr/local/nginx/sbin/nginx -s reload //重新加載配置文件/usr/local/nginx/sbin/nginx -s reopen //重新打開日志文件/usr/local/nginx/sbin/nginx -s stop //停止nginx服務/usr/local/nginx/sbin/nginx -s quit //優雅停止nginx服務/usr/local/nginx/sbin/nginx -c /path/nginx.conf //指定配置文件路徑/usr/local/nginx/sbin/nginx -t -c /path/to/nginx.conf //測試配置文件### nginx 日志文件詳解#### nginx 日志文件分為 log_format 和 access_log 兩部分##### log_format 定義記錄的格式,其語法格式為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"';變量名 說明 $remote_addr 客戶端IP地址$remote_user 客戶端用戶名$time_local 本地時間$request 請求行$status 響應狀態碼$body_bytes_sent 響應體大小$http_referer 請求來源$http_user_agent 客戶端瀏覽器信息$http_x_forwarded_for 客戶端真實IP地址$upstream_addr 上游服務器地址$upstream_response_time 上游服務器響應時間$upstream_connect_time 上游服務器連接時間$upstream_header_time 上游服務器響應頭時間$request_time 請求處理時間$msec 當前時間戳$pid 進程ID$connection 連接ID$request_length 請求長度$bytes_sent 響應字節數$http_cookie Cookie信息$http_accept 客戶端支持的類型$http_accept_language 客戶端支持的語言$http_accept_encoding 客戶端支持的編碼$http_cache_control 客戶端緩存控制$http_if_modified_since 客戶端緩存時間$http_if_none_match 客戶端緩存標識$http_range 客戶端請求的范圍$http_upgrade 客戶端請求的協議$http_origin 客戶端請求的源$http_dnt 客戶端請求的DNT$http_x_requested_with 客戶端請求的X-Requested-With$http_x_forwarded_proto 客戶端請求的協議$http_x_forwarded_port 客戶端請求的端口$http_x_forwarded_host 客戶端請求的主機$http_x_forwarded_scheme 客戶端請求的協議$http_x_forwarded_server 客戶端請求的服務器$http_x_forwarded_uri 客戶端請求的URI$http_x_forwarded_for 客戶端請求的IP地址
## 使用 limit_rate 限制客戶端傳輸數據的速度### 編輯/etc/nginx/nginx.confserver {listen 80;server_name localhost;location / {root /usr/share/nginx/html;index index.html index.htm;limit_rate 100k; //限制客戶端傳輸數據的速度為100KB/s}error_page 404 /404.html;location = /40x.html {}error_page 500 502 503 504 /50x.html;location = /50x.html {}}
## nginx 虛擬機配置### nginx可以實現虛擬主機的配置,nginx支持三種類型的虛擬主機配置。基于域名的虛擬主機 (server_name來區分虛擬主機——應用:外部網站)基于IP的虛擬主機 (server_name來區分虛擬主機——應用:外部網站)基于端口的虛擬主機 (server_name來區分虛擬主機——應用:外部網站)### 基于域名的虛擬主機配置#### 配置通過域名區分的虛擬機server {listen 80;server_name www.example.com; //設置服務器名稱location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}server {listen 80;server_name www.example2.com; //設置服務器名稱location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### 為域名的虛擬機創建indiex文件mkdir -p /usr/share/nginx/html/www.example.commkdir -p /usr/share/nginx/html/www.example2.comecho "www.example.com" > /usr/share/nginx/html/www.example.com/index.htmlecho "www.example2.com" > /usr/share/nginx/html/www.example2.com/index.html#### 重新加載配置文件nginx -s reload/usr/local/nginx/sbin/nginx -s reload#### 客戶端配置路由映射vim /etc/hosts### 基于ip的虛擬主機配置#### 配置通過ip區分的虛擬機server {listen 192.168.12.110:80; //設置服務器名稱server_name www.example.com; //設置服務器名稱 location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}server { listen 192.168.12.111:80; //設置服務器名稱server_name www.example2.com; //設置服務器名稱location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### 為ip的虛擬機創建indiex文件mkdir -p /usr/share/nginx/html/www.example.commkdir -p /usr/share/nginx/html/www.example2.comecho "www.example.com" > /usr/share/nginx/html/www.example.com/index.htmlecho "www.example2.com" > /usr/share/nginx/html/www.example2.com/index.html#### 重新加載配置文件nginx -s reload/usr/local/nginx/sbin/nginx -s reload#### 客戶端配置路由映射vim /etc/hosts#### 重啟nginxsystemctl restart nginx/usr/local/nginx/sbin/nginx -s reload### 基于端口的虛擬主機配置#### 配置通過端口區分的虛擬機server {listen 80; //設置服務器名稱server_name www.example.com; //設置服務器名稱location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}server { listen 8080; //設置服務器名稱server_name www.example2.com; //設置服務器名稱location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### 為端口的虛擬機創建indiex文件mkdir -p /usr/share/nginx/html/www.example.commkdir -p /usr/share/nginx/html/www.example2.comecho "www.example.com" > /usr/share/nginx/html/www.example.com/index.htmlecho "www.example2.com" > /usr/share/nginx/html/www.example2.com/index.html#### 重新加載配置文件nginx -s reload/usr/local/nginx/sbin/nginx -s reload#### 客戶端配置路由映射vim /etc/hosts#### 重啟nginxsystemctl restart nginx/usr/local/nginx/sbin/nginx -s reload
Nginx進階-常見配置
## nginx Proxy 反向代理### 反向代理是指客戶端請求一個服務器,服務器將請求轉發到另一個服務器上,然后將響應返回給客戶端。### 正/反向代理的區別#### 正向代理的過程隱藏了真實的請求客戶端,服務器不知道真實的客戶端是誰,客戶端請求的服務都被代理服務器代替請求。#### 反向代理的過程隱藏了真實的服務器,客戶不知道真正提供服務的人是誰,客戶端請求的服務都被代理服務器處理。反向代理代理的是響應方,也就是服務端;### nginx Proxy 配置#### 相關代理模塊##### ngx_http_proxy_module##### ngx_http_fastcgi_module##### ngx_http_uwsgi_module##### ngx_http_scgi_module##### ngx_http_memcached_module#### 啟用 nginx proxy 代理##### 環境兩臺nginx真實服務器##### nginx-1 啟動網站(內容)(yum安裝作為應用服務器)(192.168.12.110)##### nginx-2 啟動nginx反向代理(yum安裝作為代理服務器)(yum)###### 編輯yum安裝的nginx的配置文件:vim /etc/nginx/cond.d/default.confserver {listen 80;server_name localhost;location / {proxy_pass http://192.168.12.110:80; //設置代理服務器地址(nginx-1)proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}##### 重新加載nginx配置文件nginx -s reload/usr/local/nginx/sbin/nginx -s reload##### 啟動nginx-1systemctl start nginx/usr/local/nginx/sbin/nginx##### 啟動nginx-2systemctl start nginx/usr/local/nginx/sbin/nginx
## Nginx負載均衡### upstream配置#### upstream配置upstream backend {server 192.168.12.111:8081;server 192.168.12.112:8081;}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置負載均衡服務器地址proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}#### 負載均衡算法###### 輪詢(默認)--按順序分配請求###### 權重--按權重分配請求###### ip_hash--根據客戶端IP地址分配請求###### least_conn--最少連接數分配請求###### fair--根據響應時間分配請求###### random--隨機分配請求###### url_hash--根據請求URL分配請求,使每個url定向到同一個后端服務器。### 配置實例##### 輪詢(默認)upstream backend {server 192.168.12.111:8081;server 192.168.12.112:8081;}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置負載均衡服務器地址proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}#### 熱備份upstream backend {server 192.168.12.111:8081;server 192.168.12.112:8081 backup; //設置熱備份服務器}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置負載均衡服務器地址proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}#### 權重upstream backend {server 192.168.12.111:8081 weight=3; //設置權重server 192.168.12.112:8081 weight=1; //設置權重}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置負載均衡服務器地址proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}#### ip_hashupstream backend {ip_hash; //設置ip_hashserver 192.168.12.111:8081; //設置ip_hashserver 192.168.12.112:8081; //設置ip_hash}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置負載均衡服務器地址proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}#### least_connupstream backend {least_conn; //設置least_connserver 192.168.12.111:8081; //設置least_connserver 192.168.12.112:8081; //設置least_conn}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置負載均衡服務器地址proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}#### fairupstream backend {fair; //設置fairserver 192.168.12.111:8081; //設置fairserver 192.168.12.112:8081; //設置fair}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置負載均衡服務器地址proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}#### randomupstream backend {random; //設置randomserver 192.168.12.111:8081; //設置randomserver 192.168.12.112:8081; //設置random}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置負載均衡服務器地址proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}#### url_hashupstream backend {url_hash; //設置url_hashserver 192.168.12.111:8081; //設置url_hashserver 192.168.12.112:8081; //設置url_hash}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置負載均衡服務器地址proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}### nginx配置7層協議#### 7層協議:OSI(Open System Interconnection)是一個開放性的通行系統互連參考模型,他是一個定義的非常好的協議規范,共包含七層協議。應用層(Application Layer)表示層(Presentation Layer)會話層(Session Layer)傳輸層(Transport Layer)網絡層(Network Layer)數據鏈路層(Data Link Layer)物理層(Physical Layer)#### 協議配置##### 在nginx做負載均衡,負載多個服務,部分服務是需要7層的,部分服務是需要4層的,也就是說7層和4層配置在同一個配置文件中。##### 準備三臺機器:代理服務器(nginx-0)192.168.12.110應用服務器(nginx-1)192.168.12.111應用服務器(nginx-2)192.168.12.112##### nginx-0 作為代理服務器####### 編輯nginx-0的配置文件vim /etc/nginx/conf.d/default.confworker_processes 4;events {worker_connections 1024;}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 /var/log/nginx/access.log main;sendfile on;keepalive_timeout 65;gzip on;upstream backend {server 192.168.12.111:8081 weight=2 max_fails=2 fail_timeout=2s; //設置nginx-1server 192.168.12.112:8081 weight=2 max_fails=2 fail_timeout=2s; //設置nginx-2}server {listen 80;server_name localhost;charset utf-8;location / {proxy_pass http://backend; //設置nginx-1和nginx-2proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {root html;}}}####### 重新加載nginx配置文件nginx -s reload/usr/local/nginx/sbin/nginx -s reload####### 啟動nginx-0systemctl start nginx/usr/local/nginx/sbin/nginx##### 192.168.12.111\192.168.12.112 服務器yum安裝的創建新的配置文件;###### 編輯配置文件vim /etc/nginx/conf.d/default.confserver {listen 8081;server_name localhost;location / {root /usr/share/nginx/html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}###### 為nginx-1和nginx-2創建index文件mkdir -p /usr/share/nginx/htmlecho "nginx-1" > /usr/share/nginx/html/index.htmlecho "nginx-2" > /usr/share/nginx/html/index.html###### 重新加載nginx配置文件nginx -s reload/usr/local/nginx/sbin/nginx -s reload###### 啟動nginx-1和nginx-2systemctl start nginx/usr/local/nginx/sbin/nginx##### 測試nginx-0###### curl -I http://192.168.12.110 //測試nginx-0##### nginx 配置后端健康檢查模塊###### 編輯nginx-0的配置文件vim /etc/nginx/conf.d/default.confupstream backend {server 192.168.12.111:8081 weight=2 max_fails=2 fail_timeout=2s; //設置nginx-1server 192.168.12.112:8081 weight=2 max_fails=2 fail_timeout=2s; //設置nginx-2check interval=2000 rise=2 fall=5 timeout=1000; //設置健康檢查check_http_send "GET / HTTP/1.0\r\n\r\n" type=http port=8081; //設置健康檢查check_http_expect_alive http_2xx http_3xx; //設置健康檢查}server {listen 80;server_name localhost;charset utf-8;location / {proxy_pass http://backend; //設置nginx-1和nginx-2proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}error_page 404 /404.html; //設置404錯誤頁面location = /status {check_status; //設置健康檢查狀態access_log off; //關閉訪問日志}location = /40x.html {root html;}}##### 參數解釋###### interval=2000 //設置健康檢查間隔時間###### rise=2 //設置健康檢查成功次數###### fall=5 //設置健康檢查失敗次數###### timeout=1000 //設置健康檢查超時時間###### check_http_send "GET / HTTP/1.0\r\n\r\n" type=http port=8081; //設置健康檢查請求###### check_http_expect_alive http_2xx http_3xx; //設置健康檢查響應###### interval:表示每隔多少毫秒向后端發送健康檢查包###### rise:表示連續多少次健康檢查成功后,認為后端服務器是健康的###### fall:表示連續多少次健康檢查失敗后,認為后端服務器是不可用的###### timeout:表示健康檢查的超時時間###### check_http_send:表示健康檢查發送的請求###### check_http_expect_alive:表示健康檢查響應的狀態碼###### type:表示發送的健康檢查包是什么類型的請求;###### port:表示發送的健康檢查包的端口號;### 4層協議方法(擴展)#### TCP/IP協議:之所以說TCP/IP是一個協議族,是因為TCP/IP協議包括TCP、IP、UDP、ICMP、RIP、SMTP、ARP、TFTP等許多協議,這些協議一起稱為TCP/IP協議。#### TCP/IP協議分為四層應用層(Application Layer)傳輸層(Transport Layer)網絡層(Network Layer)數據鏈路層(Data Link Layer)#### TCP/IP協議的工作原理TCP/IP協議是一個分層的協議族,每一層都有自己的協議,每一層都可以獨立工作,每一層都可以使用不同的協議。TCP/IP協議的工作原理是將數據從應用層傳輸到數據鏈路層,然后通過網絡層和傳輸層進行路由和傳輸,最后到達目標主機的應用層。TCP/IP協議的工作原理是將數據從應用層傳輸到數據鏈路層,然后通過網絡層和傳輸層進行路由和傳輸,最后到達目標主機的應用層。#### 配置案例:##### 編輯nginx-0的配置文件vim /etc/nginx/conf.d/default.confstream {upstream backend {server 192.168.12.111;}server {listen 3306;proxy_pass backend;proxy_connect_timeout 1s;proxy_timeout 3s;}}##### stream塊是與http塊同一級別
## nginx 會話保持### nginx會話保持是指在負載均衡的情況下,客戶端的請求會被轉發到同一臺后端服務器上,以保持會話的一致性。### nginx會話保持的實現方式有兩種:#### 1. cookie會話保持##### cookie會話保持是通過在響應頭中添加一個cookie來實現的,nginx會將這個cookie發送給客戶端,客戶端在下次請求時會將這個cookie發送給nginx,nginx會根據這個cookie將請求轉發到同一臺后端服務器上。##### 配置實例upstream backend {server 192.168.12.111:8081;server 192.168.12.112:8081;sticky; //設置cookie會話保持# sticky expires=1h domain=testpm.com path=/; //設置cookie會話保持(二選一即可)}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置nginx-1和nginx-2proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}###### 說明####### sticky:表示開啟cookie會話保持####### expires:表示cookie的過期時間####### domain:表示cookie的域名####### path:表示cookie的路徑##### 2. ip_hash會話保持##### ip_hash會話保持是通過在nginx的upstream模塊中添加ip_hash指令來實現的,nginx會根據客戶端的IP地址將請求轉發到同一臺后端服務器上。##### 配置實例upstream backend {ip_hash; //設置ip_hash會話保持server 192.168.12.111;server 192.168.12.112;ip_hash; //設置ip_hash會話保持}server {listen 80;server_name localhost;location / {proxy_pass http://backend; //設置nginx-1和nginx-2proxy_redirect default; //設置代理服務器地址proxy_set_header Host $http_host; //設置請求頭部字段proxy_set_header X-Real-IP $remote_addr; //設置真實IP地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; //設置X-Forwarded-For請求頭部字段proxy_connect_timeout 30; //設置連接超時時間proxy_send_timeout 30; //設置發送超時時間proxy_read_timeout 30; //設置讀取超時時間proxy_buffer_size 128k; //設置代理緩沖區大小proxy_buffers 4 256k; //設置代理緩沖區數量和大小}}
## nginx 實現動靜分離### 為了加快網站的解析速度,可以把動態頁面和靜態頁面由不同的服務器來解析,加快解析速度。降低原來單個服務器的壓力。 簡單來說,就是使用正則表達式匹配過濾,然后交個不同的服務器。### 準備環境#### 準備三臺nginx服務器,準備一個nginx代理 兩個http 分別處理動態和靜態。#### nginx-0 作為代理服務器##### 編輯nginx-0的配置文件vim /etc/nginx/conf.d/default.confupstream static {server 192.168.12.111:8081 weight=1 max_fails=1 fail_timeout=60s;}upstream php { server 192.168.12.112:8081 weight=1 max_fails=1 fail_timeout=60s;} server {listen 80;server_name localhost;location ~ .*\.(html|jpg|png|css|js)$ {proxy_pass http://static;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}location ~ \.(php|jsp)$ {proxy_pass http://php;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}}#### nginx-1 作為靜態服務器##### 編輯nginx-1的配置文件vim /etc/nginx/conf.d/default.confserver {listen 8081;server_name localhost;location ~ \.(html|jpg|png|js|css) {root /usr/share/nginx/html; //設置網站根目錄expires 30d; //設置過期時間}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### nginx-2 作為動態服務器##### 編輯nginx-2的配置文件vim /etc/nginx/conf.d/default.confserver {listen 8081;server_name localhost;location ~ \.(php|jsp) {root /usr/share/nginx/html; //設置網站根目錄fastcgi_pass 127.0.0.1:9000; //設置fastcgi服務器地址fastcgi_index index.php; //設置fastcgi默認首頁文件fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; //設置fastcgi參數include fastcgi_params; //包含fastcgi參數文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### 為nginx-1和nginx-2創建index文件##### 創建index文件mkdir -p /usr/share/nginx/htmlecho "nginx-1" > /usr/share/nginx/html/index.htmlecho "nginx-2" > /usr/share/nginx/html/index.html##### 創建靜態文件 mkdir -p /usr/share/nginx/html/staticecho "static" > /usr/share/nginx/html/static/index.htmlecho "static" > /usr/share/nginx/html/static/index.jpgecho "static" > /usr/share/nginx/html/static/index.pngecho "static" > /usr/share/nginx/html/static/index.cssecho "static" > /usr/share/nginx/html/static/index.js##### 創建動態文件 mkdir -p /usr/share/nginx/html/dynamicecho "dynamic" > /usr/share/nginx/html/dynamic/index.phpecho "dynamic" > /usr/share/nginx/html/dynamic/index.jspecho "dynamic" > /usr/share/nginx/html/dynamic/index.phpecho "dynamic" > /usr/share/nginx/html/dynamic/index.jsp##### 創建404文件mkdir -p /usr/share/nginx/htmlecho "404" > /usr/share/nginx/html/404.htmlecho "404" > /usr/share/nginx/html/50x.html##### 創建50x文件 mkdir -p /usr/share/nginx/htmlecho "50x" > /usr/share/nginx/html/50x.htmlecho "50x" > /usr/share/nginx/html/50x.html
## nginx的localtion指令詳解### Nginx 的 HTTP 配置主要包括三個區塊,結構如下:http { //這個是協議級別include mime.types; //包含mime類型文件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 /var/log/nginx/access.log main; //設置訪問日志sendfile on; //開啟sendfilekeepalive_timeout 65; //設置keepalive超時時間gzip on; //開啟gzip壓縮server { //這個是服務器級別listen 80; //監聽80端口server_name localhost; //設置服務器名稱location / { //這個是請求級別root html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}}### location 區段#### location 區段是 Nginx 配置文件中用于匹配請求 URI 的指令,可以根據請求 URI 的不同來執行不同的操作。#### location 區段的語法格式如下:location [modifier] uri {# 處理請求的指令}#### location 區段的修飾符###### =: 精確匹配###### ~: 正則匹配(區分大小寫)###### ~*: 正則匹配(不區分大小寫)###### ^~: 前綴匹配(優先級高于正則匹配)###### /: 前綴匹配### 查找順序和優先級#### location 區段的查找順序和優先級如下:1. 精確匹配(=)2. 正則匹配(~)3. 前綴匹配(^~)4. 前綴匹配(/)### location 配置示例#### 沒有修飾符 表示:必須以指定模式開始server {listen 80;server_name localhost;location /abc123 {root html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### =表示:必須與指定的模式精確匹配server {listen 80;server_name localhost;location = /abc123 {Return return https://www.baidu.com; //設置重定向}location / {Return return https://www.jd.com; //設置重定向}}#### ~表示:必須與指定的模式正則匹配(區分大小寫)server {listen 80;server_name localhost;location ~ \.php$ {root html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### ~*表示:必須與指定的模式正則匹配(不區分大小寫)server {listen 80;server_name localhost;location ~* \.php$ {root html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### ^~表示:必須與指定的模式前綴匹配(優先級高于正則匹配)server {listen 80;server_name localhost;location ^~ /abc123 {root html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### /表示:必須與指定的模式前綴匹配server {listen 80;server_name localhost;location /abc123 {root html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}} #### location 區段的參數###### root: 設置網站根目錄###### index: 設置默認首頁文件###### alias: 設置別名###### try_files: 嘗試訪問文件###### expires: 設置過期時間###### add_header: 添加響應頭部字段###### proxy_pass: 設置代理服務器地址###### proxy_redirect: 設置代理服務器地址###### proxy_set_header: 設置請求頭部字段###### proxy_connect_timeout: 設置連接超時時間###### proxy_send_timeout: 設置發送超時時間###### proxy_read_timeout: 設置讀取超時時間###### proxy_buffer_size: 設置代理緩沖區大小###### proxy_buffers: 設置代理緩沖區數量和大小
## nginx 地址重寫 rewrite### 什么是Rewrite#### Rewrite是Nginx的一個模塊,用于對請求的URL進行重寫和重定向。#### Rewrite可以根據請求的URL進行匹配,并將其重寫為指定的URL。#### Rewrite可以用于實現URL的美化、301重定向、404頁面等功能。### Rewrite 相關指令#### rewrite: 用于對請求的URL進行重寫#### return: 用于對請求的URL進行重定向#### set: 用于設置變量#### if: 用于條件判斷#### if語句##### 應用環境server、location##### 語法格式if ($variable) {# 處理請求的指令} ##### 語法說明if: 用于條件判斷$variable: 用于判斷的變量# 處理請求的指令: 用于處理請求的指令##### if 可以支持如下條件判斷匹配符號=: 精確匹配~: 正則匹配(區分大小寫)~*: 正則匹配(不區分大小寫)^~: 前綴匹配(優先級高于正則匹配)/: 前綴匹配-f、!-f: 判斷文件是否存在-d、!-d: 判斷目錄是否存在-e、!-e: 判斷文件或目錄是否存在-x、!-x: 判斷文件是否可執行##### 在匹配過程中可以引用一些Nginx的全局變量$args: 請求參數$document_root: 網站根目錄$host: 主機名$limit_rate: 限制下載速度$remote_method: 請求方法$remote_addr: 客戶端IP地址$remote_port: 客戶端端口$remote_user: 客戶端用戶名$request_filename: 請求文件名$request_uri: 請求URIquery_string: 查詢字符串$scheme: 協議類型$server_protocol: 協議版本$server_name: 服務器名稱$server_addr: 服務器IP地址$document_ruit: 網站根目錄$server_port: 服務器端口#### Rewrite flag##### last: 停止當前的rewrite規則,繼續執行后面的location##### break: 停止當前的rewrite規則,不再執行后面的rewrite規則##### redirect: 返回302臨時重定向##### permanent: 返回301永久重定向##### 參考案例http://www.testpm.com/a/1.html ==> http://www.testpm.com/b/2.htmllocation /a {root /html;index 1.html index.htm;rewrite .* /b/2.html permanent;}location /b {root /html;index 2.html index.htm;}http://www.testpm.com/2019/a/1.html ==> http://www.testpm.com/2018/a/1.htmllocation /2019/a {root /var/www/html;index 1.html index.hml;rewrite ^/2019/(.*)$ /2018/$1 permanent;}location /2018/a {root /var/www/html;index 1.html index.htl;}http://www.qf.com/a/1.html ==> http://jd.comlocation /a {root /html;if ($host ~* www.qf.com ) {rewrite .* http://jd.com permanent;}}http://www.qf.com/a/1.html ==> http://jd.com/a/1.htmllocation /a {root /html;if ( $host ~* qf.com ){rewrite .* http://jd.com$request_uri permanent;}}http://www.tianyun.com/login/tianyun.html ==> http://www.tianyun.com/reg/login.html?user=tianyunlocation /login {root /usr/share/nginx/html;rewrite ^/login/(.*)\.html$ http://$host/reg/login.html?user=$1;}location /reg {root /usr/share/nginx/html;index login.html;}http://www.tianyun.com/qf/11-22-33/1.html ==> http://www.tianyun.com/qf/11/22/33/1.htmllocation /qf {rewrite ^/qf/([0-9]+)-([0-9]+)-([0-9]+)(.*)$ /qf/$1/$2/$3$4 permanent;}location /qf/11/22/33 {root /html;index 1.html;}#### set 指令##### set 指令是用于定義一個變量,并且賦值##### 應用環境server、location、if##### 應用示例http://alice.testpm.com ==> http://www.testpm.com/alicehttp://jack.testpm.com ==> http://www.testpm.com/jack[root@nginx-server conf.d]# cd /usr/share/nginx/html/[root@nginx-server html]# mkdir jack alice[root@nginx-server html]# echo "jack.." >> jack/index.html[root@nginx-server html]# echo "alice.." >> alice/index.html本地解析域名host文件10.0.105.202 www.testpm.com10.0.105.202 alice.testpm.com10.0.105.202 jack.testpm.com編輯配置文件:server {listen 80;server_name www.testpm.com;location / {root /usr/share/nginx/html;index index.html index.htm;if ( $host ~* ^www.testpm.com$) {break;}if ( $host ~* "^(.*)\.testpm\.com$" ) {set $user $1;rewrite .* http://www.testpm.com/$user permanent;}}location /jack {root /usr/share/nginx/html;index index.html index.hml;}location /alice {root /usr/share/nginx/html;index index.html index.hml;}}#### return 指令##### return 指令用于返回狀態碼給客戶端##### 應用示例如果訪問的.sh結尾的文件則返回403操作拒絕錯誤server {listen 80;server_name www.testpm.cn;#access_log /var/log/nginx/http_access.log main;location / {root /usr/share/nginx/html;index index.html index.htm;}location ~* \.sh$ {return 403;}}80 ======> 443 :80轉443端口server {listen 80;server_name www.testpm.cn;access_log /var/log/nginx/http_access.log main;return 301 https://www.testpm.cn$request_uri;}server {listen 443 ssl;server_name www.testpm.cn;access_log /var/log/nginx/https_access.log main;#ssl on;ssl_certificate /etc/nginx/cert/2447549_www.testpm.cn.pem;ssl_certificate_key /etc/nginx/cert/2447549_www.testpm.cn.key;ssl_session_timeout 5m;ssl_protocols TLSv1 TLSv1.1 TLSv1.2;ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;ssl_prefer_server_ciphers on;location / {root /usr/share/nginx/html;index index.html index.htm;}}#### last,break詳解##### last: 停止當前的rewrite規則,繼續執行后面的location##### break: 停止當前的rewrite規則,不再執行后面的rewrite規則##### 參考案例http://www.testpm.com/a/1.html ==> http://www.testpm.com/b/2.htmllocation /a {root /html;index 1.html index.htm;rewrite .* /b/2.html last;}location /b {root /html;index 2.html index.htm;}http://www.testpm.com/a/1.html ==> http://www.testpm.com/b/2.htmllocation /a {root /html;index 1.html index.htm;rewrite .* /b/2.html break;}location /b {root /html;index 2.html index.htm;}
## nginx 日志配置### nginx 日志介紹#### nginx 日志分為兩種類型1. 訪問日志(access log)2. 錯誤日志(error log)#### nginx 日志的格式1. 訪問日志格式$remote_addr: 客戶端IP地址$remote_user: 客戶端用戶名$time_local: 請求時間$request: 請求方法和請求URI$status: 響應狀態碼$body_bytes_sent: 響應體大小$http_referer: 請求來源地址$http_user_agent: 客戶端瀏覽器信息2. 錯誤日志格式$time_local: 請求時間$pid: 進程ID$level: 日志級別$message: 日志信息3. path 指定日志的存放位置。4. 作用域http: 全局作用域server: 服務器作用域location: 請求作用域### log_format 指令#### log_format 指令用于定義訪問日志的格式#### log_format 指令的語法格式如下:log_format name format;#### log_format 指令的參數name: 日志格式名稱format: 日志格式#### 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"';#### 如果不想使用Nginx預定義的格式,可以通過log_format指令來自定義。##### 語法log_format name [escape=default|json] string ...;- name 格式名稱。在 access_log 指令中引用。 - escape=default|json 選擇轉義字符。默認值為 default。- string 訪問日志格式字符串。可以包含變量和文本。##### 變量$remote_addr: 客戶端IP地址$remote_user: 客戶端用戶名$time_local: 請求時間$request: 請求方法和請求URI$status: 響應狀態碼$body_bytes_sent: 響應體大小$http_referer: 請求來源地址$http_user_agent: 客戶端瀏覽器信息$http_x_forwarded_for: X-Forwarded-For請求頭部字段$request_time: 請求時間$upstream_response_time: 上游服務器響應時間$upstream_addr: 上游服務器地址$upstream_cache_status: 上游緩存狀態$upstream_connect_time: 上游服務器連接時間$upstream_header_time: 上游服務器響應頭時間$upstream_bytes_sent: 上游服務器發送的字節數$upstream_bytes_received: 上游服務器接收的字節數$time_iso8601: ISO 8601格式的時間$time_local: 本地時間$msec: 毫秒級時間戳#### 自定義日志格式的使用access_log /var/logs/nginx-access.log mainlog_format main'$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';注意:如果Nginx位于負載均衡器,nginx反向代理之后,web服務器無法直接獲取到客戶端真實的IP地址。解決方法:在nginx.conf中添加proxy_set_header X-Forwarded-For $remote_addr;指令。#### 訪問日志的配置access_log /var/log/nginx/access.log main;access_log /var/log/nginx/access.log combined;access_log /var/log/nginx/access.log custom;面試時:注意日志里面的ip地址一定要在第一列### error_log 指令#### 錯誤日志在Nginx中是通過error_log指令實現的。該指令記錄服務器和請求處理過程中的錯誤信息。#### error_log 指令的語法配置錯誤日志文件的路徑和日志級別error_log file [level];Default: error_log logs/error.log error;#### file 參數指定日志的寫入位置#### level 參數指定日志的級別debug: 調試信息info: 一般信息notice: 注意信息warn: 警告信息error: 錯誤信息crit: 嚴重錯誤信息alert: 緊急錯誤信息emerg: 緊急錯誤信息#### error_log 指令的示例error_log /var/log/nginx/error.log;error_log /var/log/nginx/error.log info;error_log /var/log/nginx/error.log warn;error_log /var/log/nginx/error.log error;error_log /var/log/nginx/error.log crit;error_log /var/log/nginx/error.log alert;error_log /var/log/nginx/error.log emerg;#### 配置段: http, server, location作用域。### nginx 日志配置總結#### 訪問日志access_log /var/log/nginx/access.log main;access_log /var/log/nginx/access.log combined;access_log /var/log/nginx/access.log custom;#### 錯誤日志error_log /var/log/nginx/error.log;error_log /var/log/nginx/error.log info;error_log /var/log/nginx/error.log warn;error_log /var/log/nginx/error.log error;error_log /var/log/nginx/error.log crit;error_log /var/log/nginx/error.log alert;error_log /var/log/nginx/error.log emerg;#### 日志格式log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';log_format combined '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';log_format custom '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';
## nginx 的平滑升級### 什么是平滑升級#### 平滑升級是指在不影響用戶訪問的情況下,對Nginx進行升級和配置修改。#### 平滑升級可以避免服務中斷和用戶請求丟失。### 平滑升級的實現方式#### 1. 使用nginx -s reload命令##### nginx -s reload命令用于重新加載Nginx配置文件,并且不影響正在進行的連接。##### 該命令會先將新的配置文件加載到內存中,然后再關閉舊的工作進程,最后啟動新的工作進程。#### 2. 使用nginx -s reopen命令##### nginx -s reopen命令用于重新打開Nginx日志文件,并且不影響正在進行的連接。##### 該命令會先關閉舊的日志文件,然后再打開新的日志文件。#### 3. 使用nginx -t命令##### nginx -t命令用于測試Nginx配置文件的語法是否正確,并且不影響正在進行的連接。##### 該命令會先檢查配置文件的語法,然后再檢查配置文件中的路徑是否存在。### nginx 錯誤頁面配置#### 1. 錯誤頁面的配置##### error_page指令用于配置錯誤頁面##### error_page指令的語法格式如下:error_page code [code ...] uri;##### error_page指令的參數code: 錯誤狀態碼uri: 錯誤頁面的URI##### error_page指令的示例error_page 404 /404.html;error_page 500 502 503 504 /50x.html;#### 2. 錯誤頁面的使用##### 錯誤頁面可以是靜態頁面,也可以是動態頁面##### 靜態頁面的使用示例server {listen 80;server_name localhost;location / {root html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.html; //設置404錯誤頁面location = /40x.html {}error_page 500 502 503 504 /50x.html; //設置50x錯誤頁面location = /50x.html {}}#### 3. 動態頁面的使用示例##### 動態頁面的使用示例server {listen 80;server_name localhost;location / {root html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.php; //設置404錯誤頁面location = /40x.php {root html; //設置網站根目錄index index.php index.htm; //設置默認首頁文件}error_page 500 502 503 504 /50x.php; //設置50x錯誤頁面location = /50x.php {root html; //設置網站根目錄index index.php index.htm; //設置默認首頁文件}}#### 4. 錯誤頁面的重定向##### 錯誤頁面的重定向示例server {listen 80;server_name localhost;location / {root html; //設置網站根目錄index index.html index.htm; //設置默認首頁文件}error_page 404 /404.php; //設置404錯誤頁面location = /40x.php {return 301 http://www.baidu.com; //設置重定向}error_page 500 502 503 504 /50x.php; //設置50x錯誤頁面location = /50x.php {return 301 http://www.baidu.com; //設置重定向}}
## nginx 流量控制流量限制 (rate-limiting),我們可以用來限制用戶在給定時間內HTTP請求的數量。流量限制可以用作安全目的,比如可以減慢暴力密碼破解的速率,更常見的情況是該功能被用來保護上游應用服務器不被同時太多用戶請求所壓垮。### Nginx如何限流Nginx的”流量限制”使用漏桶算法(leaky bucket algorithm),就好比,一個桶口在倒水,桶底在漏水的水桶。如果桶口倒水的速率大于桶底的漏水速率,桶里面的水將會溢出;同樣,在請求處理方面,水代表來自客戶端的請求,水桶代表根據”先進先出調度算法”(FIFO)等待被處理的請求隊列,桶底漏出的水代表離開緩沖區被服務器處理的請求,桶口溢出的水代表被丟棄和不被處理的請求。### 配置基本的限流--ngx_http_limit_req_module模塊實現#### “流量限制”配置兩個主要的指令,limit_req_zone和limit_req,limit_req_zone指令設置流量限制和內存區域的參數,但實際上并不限制請求速率。所以需要通過添加limit_req指令啟用流量限制,應用在特定的location或者server塊。(示例中,對于”/login/”的所有請求)。limit_req_zone指令通常在HTTP塊中定義,它需要以下三個參數:-Key - 定義應用限制的請求特性。示例中的 Nginx 變量$binary_remote_addr,保存客戶端IP地址的二進制形式。-Zone -定義用于存儲每個IP地址狀態以及被限制請求URL訪問頻率的內存區域。通過zone=keyword標識區域的名字(自定義),以及冒號后面跟區域大小。16000個IP地址的狀態信息,大約需要1MB。-Rate -連接請求。在示例中,速率不能超過每秒1個請求。##### 示例一limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;upstream myweb {server 192.168.12.149:80 weight=1 max_fails=1 fail_timeout=1;}server {listen 80;server_name localhost;location /login {limit_req zone=mylimit;proxy_pass http://myweb;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}}##### 示例二limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;upstream myweb {server 192.168.12.149:80 weight=1 max_fails=1 fail_timeout=1;}server {listen 80;server_name localhost;location /login {#limit_req zone=mylimit;limit_req zone=mylimit burst=5;#limit_req zone=mylimit burst=5 nodelay;proxy_pass http://myweb;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}}##### nginx日志字段- limiting requests - 表明日志條目記錄的是被“流量限制”請求- excess - 每毫秒超過對應“流量限制”配置的請求數量- zone - 定義實施“流量限制”的區域- client - 發起請求的客戶端IP地址- server - 服務器IP地址或主機名- request - 客戶端發起的實際HTTP請求- host - HTTP報頭中host的值##### 發送到客戶端的錯誤代碼一般情況下,客戶端超過配置的流量限制時,Nginx響應狀態碼為503(Service Temporarily Unavailable)。可以使用limit_req_status指令來設置為其它狀態碼(例如下面的404狀態碼):limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;upstream myweb {server 192.168.12.149:80 weight=1 max_fails=1 fail_timeout=1;}server {listen 80;server_name localhost;location /login {limit_req zone=mylimit;limit_req_status 404;proxy_pass http://myweb;proxy_set_header Host $host:$server_port;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}}
## nginx 訪問控制### nginx 訪問控制模塊基于IP的訪問控制:http_access_module基于用戶的信任登錄:http_auth_basic_module### 基于IP的訪問控制http_access_module模塊可以限制IP地址的訪問權限。可以允許或拒絕特定的IP地址或IP地址范圍訪問Nginx服務器。#### 配置語法Syntax:allow address | all;default:默認無Context:http,server,locationSyntax:deny address | all;default:默認無Context:http,server,location===================================================allow 允許 //ip或者網段deny 拒絕 //ip或者網段#### 配置測試編輯/etc/nginx/conf.d/access_mod.conf內容如下:[root@192 ~]# vim /etc/nginx/conf.d/access_mod.confserver {listen 80;server_name localhost;location / {root /usr/share/nginx/html;index index.html index.hml;deny 192.168.12.8;allow all;}}[root@192 ~]# nginx -t[root@192 ~]# nginx -s reload#### #需要注意:1.按順序匹配,已經被匹配的ip或者網段,后面不再被匹配。2.如果先允許所有ip訪問,在定義拒絕訪問。那么拒絕訪問不生效。3.默認為allow all可以使用IP網段的配置方式,如allow 192.168.12.0/24;,表示滿足此網段的IP都可以訪問。#### 指定location拒絕所有請求server {listen 80;server_name localhost;location / {root /usr/share/nginx/html;index index.html index.hml;deny all; #拒絕所有}}### 基于用戶的信任登錄http_auth_basic_module模塊可以限制用戶的訪問權限。可以允許或拒絕特定的用戶訪問Nginx服務器。#### 配置語法Syntax:auth_basic string | off;default:auth_basic off;Context:http,server,locationSyntax:auth_basic_user_file file;default:默認無Context:http,server,locationfile:存儲用戶名密碼信息的文件。#### 配置測試編輯/etc/nginx/conf.d/access_mod.conf內容如下:[root@192 ~]# vim /etc/nginx/conf.d/access_mod.confserver {listen 80;server_name localhost;location / {root /usr/share/nginx/html;index index.html index.hml;auth_basic "Auth access test!";auth_basic_user_file /etc/nginx/auth_conf;}}[root@192 ~]# mkdir /var/www/html #創建目錄[root@192 ~]# vim /var/www/html/index.html #創建文件##### auth_basic不為off,開啟登錄驗證功能,auth_basic_user_file加載賬號密碼文件。#### 建立口令文件[root@192 ~]# yum install -y httpd-tools #htpasswd 是開源 http 服務器 apache httpd 的一個命令工具,用于生成 http 基本認證的密碼文件[root@192 ~]# htpasswd -cm /etc/nginx/auth_conf user10 # -c 創建解密文件,-m MD5加密[root@192 ~]# htpasswd -m /etc/nginx/auth_conf user20[root@192 ~]# cat /etc/nginx/auth_conf
## nginx 變量Nginx的配置文件使用語法的就是一門微型的編程語言。既然是編程語言,一般也就少不了“變量”這種東西。### nginx變量簡介#### nginx變量是Nginx配置文件中的一個特殊的字符串,用于存儲和傳遞數據。#### nginx變量可以在配置文件中使用,也可以在請求中使用。#### nginx變量的名稱以$符號開頭,后面跟變量名。#### nginx變量可以是內置變量,也可以是自定義變量。#### 在 Nginx 配置中,變量只能存放一種類型的值,而且也只存在一種類型,那就是字符串類型#### 所有的變量值都可以通過這種方式引用:$變量名### nginx 變量的定義和使用#### nginx中的變量分為兩種,自定義變量與內置預定義變量#### 自定義變量##### 自定義變量的定義和使用set $name value;set $name $value;##### 自定義變量的示例set $name "testpm";set $name $remote_addr;#### 內置預定義變量##### 內置預定義變量的定義和使用$variable##### 內置預定義變量的示例$remote_addr: 客戶端IP地址$remote_user: 客戶端用戶名$time_local: 請求時間$request: 請求方法和請求URI$status: 響應狀態碼$body_bytes_sent: 響應體大小$http_referer: 請求來源地址$http_user_agent: 客戶端瀏覽器信息$http_x_forwarded_for: X-Forwarded-For請求頭部字段$request_time: 請求時間
## nginx 監控### nginx的基礎監控- 進程監控- 端口監控注意: 這兩個是必須要加在zabbix監控,加觸發器有問題及時告警。nginx 提供了 ngx_http_stub_status_module.這個模塊提供了基本的監控功能### 監控的指標#### 基本活躍指標- Active connections: 當前活動連接數- Accepts: 已接受的連接數- Handled: 已處理的連接數- Requests: 已處理的請求數- Reading: 當前讀取請求頭的連接數- Writing: 當前發送響應頭的連接數- Waiting: 當前處于空閑狀態的連接數#### 服務器錯誤率- 4xx: 客戶端錯誤率- 5xx: 服務器錯誤率#### 請求處理時間請求處理時間也可以被記錄在 access log 中,通過分析 access log,統計請求的平均響應時間。 ----$request_time 變量#### nginx Stub Status 監控- 通過http_stub_status_module模塊來實現nginx的監控- 該模塊提供了nginx的基本狀態信息,包括活動連接數、請求數、處理時間等- 該模塊需要在nginx編譯時添加--with-http_stub_status_module參數- 該模塊需要在nginx配置文件中添加location /stub_status指令- 該模塊需要在nginx配置文件中添加allow和deny指令來限制訪問##### [root@localhost ~]# vim /etc/nginx/conf.d/status.confserver {listen 80;server_name localhost;location /nginx-status {stub_status on;access_log on;}}##### 配置完成后在瀏覽器中輸入http://<本機ip>/nginx-status 查看顯示信息##### 訪問狀態信息Active connections: 1server accepts handled requests2 2 2Reading: 0 Writing: 1 Waiting: 0##### Stub Status 參數說明Active connections: 當前活動連接數server accepts handled requests: 已接受的連接數、已處理的連接數、已處理的請求數Reading: 當前讀取請求頭的連接數Writing: 當前發送響應頭的連接數Waiting: 當前處于空閑狀態的連接數#### 基于腳本監控nginx的端口#!/usr/bin/bashcurl -I http://192.168.12.149 &> /dev/nullif [ $? -ne 0 ];thenecho "nginx 未運行,正在啟動中..."sleep 1systemctl start nginxecho "正在檢查nginx是否啟動..."port=`netstat -lntp | grep nginx |awk '{print $4}' | awk -F':' '{print $NF}'`echo "nginx已經啟動,端口為: $port"fi
## HTTPS 基本原理### https 介紹#### HTTPS是HTTP協議的安全版本,使用SSL/TLS協議對數據進行加密和解密。#### HTTPS可以保護數據的機密性、完整性和身份驗證。#### HTTPS使用SSL/TLS證書來加密數據傳輸,確保數據在傳輸過程中不被竊取或篡改。#### HTTPS使用公鑰和私鑰進行加密和解密,確保數據的安全性。### 加密算法#### 對稱加密算法- DES:數據加密標準- AES:高級加密標準- 3DES:三重數據加密標準A要給B發送數據1,A做一個對稱密鑰2,使用密鑰給文件加密3,發送加密以后的文件和鑰匙4,B拿鑰匙解密#### 非對稱加密算法- RSA:Rivest-Shamir-Adleman算法- DSA:數字簽名算法- DH:Diffie-Hellman算法A要給B發送數據1.B做一對非對稱的密鑰2.發送公鑰給A3.A拿公鑰對數據進行加密4.發送加密后的數據給B5.B拿私鑰解密#### 哈希算法- MD5:消息摘要算法- SHA-1:安全哈希算法1- SHA-2:安全哈希算法2將任意長度的信息轉換為較短的固定長度的值,通常其長度要比信息小得多。例如:MD5、SHA-1、SHA-2、SHA-256 等#### 數字證書- 數字證書是由數字證書頒發機構(CA)簽發的電子文檔,用于證明公鑰的真實性和合法性。- 數字證書包含了公鑰、證書持有者的信息、證書頒發機構的信息、證書的有效期等信息。- 數字證書使用數字簽名技術來保證數據的完整性和真實性。簽名就是在信息的后面再加上一段內容(信息經過hash后的值),可以證明信息沒有被修改過。hash值一般都會加密后(也就是簽名)再和信息一起發送,以保證這個hash值不被修改。### HTTPS 協議介紹(圖例)#### HTTPS協議的工作原理1. 客戶端向服務器發送請求,要求建立安全連接。2. 服務器返回數字證書,包含公鑰和證書信息。3. 客戶端驗證數字證書的合法性。4. 客戶端生成隨機數,用公鑰加密后發送給服務器。5. 服務器使用私鑰解密隨機數,生成會話密鑰。6. 雙方使用會話密鑰進行數據加密和解密。7. 數據傳輸完成后,關閉連接。### HTTPS 原理#### HTTP 訪問過程1. 客戶端向服務器發送請求,要求建立連接。2. 服務器返回響應,包含數據和狀態碼。3. 客戶端接收響應,處理數據。#### HTTP 傳輸面臨的風險有1. 數據被竊取:數據在傳輸過程中可能被第三方竊取。2. 數據被篡改:數據在傳輸過程中可能被第三方篡改。3. 身份偽造:第三方可能冒充服務器或客戶端進行攻擊。#### HTTP和HTTPS的區別1. HTTP是明文傳輸,HTTPS是加密傳輸。2. HTTP使用80端口,HTTPS使用443端口。3. HTTP不需要證書,HTTPS需要證書。4. HTTP不安全,HTTPS安全。### CA 機構(證書)#### CA(Certificate Authority)證書頒發機構主要負責證書的頒發、管理以及歸檔和吊銷。證書內包含了擁有證書者的姓名、地址、電子郵件帳號、公鑰、證書有效期、發放證書的CA、CA的數字簽名等信息。#### 證書主要有三大功能:加密、簽名、身份驗證。\#### 證書的類型1. 根證書:根證書是由CA機構簽發的證書,用于驗證其他證書的合法性。2. 中級證書:中級證書是由根證書簽發的證書,用于驗證其他證書的合法性。3. 服務器證書:服務器證書是由CA機構簽發的證書,用于驗證服務器的身份。4. 客戶端證書:客戶端證書是由CA機構簽發的證書,用于驗證客戶端的身份。5. 自簽名證書:自簽名證書是由自己簽發的證書,用于驗證自己的身份。6. 商業證書:商業證書是由CA機構簽發的證書,用于驗證商業網站的身份。7. 免費證書:免費證書是由CA機構簽發的證書,用于驗證個人網站的身份。#### 證書的申請1. 申請證書:向CA機構申請證書,提供相關信息。2. 驗證身份:CA機構驗證申請者的身份。3. 簽發證書:CA機構簽發證書,并發送給申請者。4. 安裝證書:將證書安裝到服務器上。5. 配置服務器:配置服務器使用HTTPS協議。6. 測試證書:測試證書是否安裝成功。7. 更新證書:定期更新證書,確保證書的有效性。#### ssl證書---實戰1. 申請ssl證書2. 下載ssl證書3. 上傳ssl證書到nginx服務器4. 配置nginx使用ssl證書5. 重啟nginx服務6. 測試ssl證書是否安裝成功