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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

nginx工作原理与配置

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

nginx工作原理與配置

文章目錄

  • nginx工作原理與配置
    • nginx的模塊與工作原理
      • nginx的模塊分類
      • nginx的工作原理
    • nginx的安裝與配置
      • nginx安裝
      • nginx配置
    • nginx的配置文件詳解
      • nginx.conf配置詳解
      • 用于調試、定位問題的配置參數
      • https配置
      • 基于用戶認證
      • 開啟狀態界面
      • URL
      • URL - 統一資源定位器
      • 常見的 URL Scheme
      • rewrite
      • if
      • 基于瀏覽器實現分離案例
      • 防盜鏈案例
      • 反向代理與負載均衡

nginx的模塊與工作原理

? nginx由內核和模塊組成。其中,內核的設計非常微小和簡潔,完成的工作也非常簡單,僅僅通過查找配置文件將客戶端請求映射到一個location block(location是nginx配置中的一個指令,用于URL匹配),而在這個location中所配置的每個指令將會啟動不同的模塊去完成相應的工作。

nginx的模塊分類

? nginx的模塊從結構上分為核心模塊、基礎模塊和第三方模塊

  • HTTP模塊、EVENT模塊和MAIL模塊等屬于核心模塊
  • HTTP Access模塊、HTTP FastCGI模塊、HTTP Proxy模塊和HTTP Rewrite模塊屬于基本模塊
  • HTTP Upstream模塊、Request Hash模塊、Notice模塊和HTTP Access Key模塊屬于第三方模塊

用戶根據自己的需要開發的模塊都屬于第三方模塊。正是有了如此多模塊的支撐,nginx的功能才會如此強大

nginx模塊從功能上分為三類,分別是:

  • Handlers(處理器模塊)。此類模塊直接處理請求,并進行輸出內容和修改headers信息等操作。handlers處理器模塊一般只能有一個
  • Filters(過濾器模塊)。此類模塊主要對其他處理器模塊輸出的內容進行修改操作,最后由nginx輸出
  • Proxies(代理器模塊)。就是nginx的HTTP Upstream之類的模塊,這些模塊主要與后端一些服務比如fastcgi等操作交互,實現服務代理和負載均衡等功能

nginx模塊分為:核心模塊、事件模塊、標準Http模塊、可選Http模塊、郵件模塊、第三方模塊和補丁等

  • nginx基本模塊:所謂基本模塊,指的是nginx默認的功能模塊,它們提供的指令,允許你使用定義nginx基本功能的變量,在編譯時不能被禁用,包括:
    • 核心模塊:基本功能和指令,如進程管理和安全。常見的核心模塊指令,大部分是放置在配置文件的頂部
    • 事件模塊:在Nginx內配置網絡使用的能力。常見的events(事件)模塊指令,大部分是放置在配置文件的頂部
    • 配置模塊:提供包含機制

nginx的工作原理

nginx的模塊直接被編譯進nginx,因此屬于靜態編譯方式。

啟動nginx后,nginx的模塊被自動加載,與Apache不一樣,首先將模塊編譯為一個so文件,然后在配置文件中指定是否進行加載。

在解析配置文件時,nginx的每個模塊都有可能去處理某個請求,但是同一個處理請求只能由一個模塊來完成。

nginx的進程架構:
啟動nginx時,會啟動一個Master進程,這個進程不處理任何客戶端的請求,主要用來產生worker線程,一個worker線程用來處理n個request。

下圖展示了nginx模塊一次常規的HTTP請求和響應的過程

下圖展示了基本的WEB服務請求步驟

nginx的安裝與配置

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' 上次元數據過期檢查:2:59:11 前,執行于 2021年10月25日 星期一 01時04分32秒。 依賴關系解決。 =============================================================軟件包 架構 版本 倉庫 大小 ============================================================= 安裝組: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 --2021-10-25 04:06:16-- http://nginx.org/download/nginx-1.12.0.tar.gz 正在解析主機 nginx.org (nginx.org)...

編譯安裝

[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配置

服務控制方式,使用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 檢查配置文件語法

[root@localhost ~]# 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

-v 輸出nginx的版本

[root@localhost ~]# nginx -v nginx version: nginx/1.20.1

-c 指定配置文件的路徑

[root@localhost ~]# nginx -s stop ; nginx -c /opt/nginx.conf ##直接停掉然后啟動 [root@localhost ~]# ps -ef|grep nginx root 99290 1 0 03:32 ? 00:00:00 nginx: master process nginx -c /opt/nginx.conf nginx 99291 99290 0 03:32 ? 00:00:00 nginx: worker process nginx 99292 99290 0 03:32 ? 00:00:00 nginx: worker process root 101138 1653 0 03:33 pts/0 00:00:00 grep --color=auto nginx

-s 發送服務控制信號,可選值有{stop|quit|reopen|reload}

[root@localhost ~]# nginx -s quit [root@localhost ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port Process LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 128 [::]:22 [::]:*

nginx的配置文件詳解

主配置文件:/usr/local/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協議相關的配置

Nginx配置文件示例

[root@localhost ~]# vim /usr/local/nginx/conf # 全局塊user www-data; ##用戶worker_processes 2; ## 默認1,一般建議設成CPU核數1-2倍error_log logs/error.log; ## 錯誤日志路徑pid logs/nginx.pid; ## 進程id# Events塊events {# 使用epoll的I/O 模型處理輪詢事件。# 可以不設置,nginx會根據操作系統選擇合適的模型use epoll;# 工作進程的最大連接數量, 默認1024個worker_connections 2048;# http層面的keep-alive超時時間keepalive_timeout 60;# 客戶端請求頭部的緩沖區大小client_header_buffer_size 2k;}# http塊http { include mime.types; # 導入文件擴展名與文件類型映射表default_type application/octet-stream; # 默認文件類型# 日志格式及access日志路徑log_format main '$remote_addr - $remote_user [$time_local] $status ''"$request" $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';access_log logs/access.log main; # 允許sendfile方式傳輸文件,默認為off。sendfile on;tcp_nopush on; # sendfile開啟時才開啟。# http server塊# 簡單反向代理server {listen 80;server_name domain2.com www.domain2.com;access_log logs/domain2.access.log main;# 轉發動態請求到web應用服務器location / {proxy_pass http://127.0.0.1:8000;deny 192.24.40.8; # 拒絕的ipallow 192.24.40.6; # 允許的ip }# 錯誤頁面error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}# 負載均衡upstream backend_server {server 192.168.0.1:8000 weight=5; # weight越高,權重越大server 192.168.0.2:8000 weight=1;server 192.168.0.3:8000;server 192.168.0.4:8001 backup; # 熱備}server {listen 80;server_name big.server.com;access_log logs/big.server.access.log main;charset utf-8;client_max_body_size 10M; # 限制用戶上傳文件大小,默認1Mlocation / {# 使用proxy_pass轉發請求到通過upstream定義的一組應用服務器proxy_pass http://backend_server;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $http_host;proxy_redirect off;proxy_set_header X-Real-IP $remote_addr;} }}

配置指令:要以分號結尾,語法格式如下:

derective value1 [value2 ...];

支持使用變量:

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

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

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


比如將配置文件中的記錄日志的注釋取消掉,然后可以修改日志級別,就有記錄了,日志級別越低,越詳細,但是無用的記錄也越多,所以我們應該選擇適當的日志級別,比如我們設置的是crit級別,但是看不出來什么錯誤,我們就可以降低級別來查看更詳細的記錄

[root@localhost ~]# ls /usr/local/nginx/logs/ ##先查看是否存在錯誤日志文件 nginx.pid [root@localhost ~]# vim /usr/local/nginx/conf/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; ·····省略部分[root@localhost ~]# nginx -s reload ##重新加載##發現已經出現了一個日志文件 [root@localhost ~]# ls /usr/local/nginx/logs/ error.log nginx.pid

瀏覽器訪問,使其產生一個錯誤日志

再去查看錯誤日志

[root@localhost ~]# cat /usr/local/nginx/logs/error.log ##里面的記錄就是上面訪問頁面的錯誤信息 2021/10/26 07:43:03 [error] 36057#0: *3 open() "/usr/local/nginx/html/liuqiang" failed (2: No such file or directory), client: 192.168.240.1, server: localhost, request: "GET /liuqiang HTTP/1.1", host: "192.168.240.60"

正常運行必備的配置參數
使用的時候直接在配置文件中指明使用的用戶是nginx
pid文件位置也取消注釋直接使用,因為默認注釋掉也是使用的這個位置,當然也可以修改為其他位置

[root@localhost conf]# vim /usr/local/nginx/conf/nginx.conf1 2 user nginx nginx; # 取消注釋,修改為nginx用戶,nginx組3 worker_processes 1; ·····省略部分·············省略部分········7 #error_log logs/error.log info;8 9 pid logs/nginx.pid; # 取消注釋·····省略部分········[root@localhost conf]# nginx -s reload # 重新加載配置文件立即生效

設置worker線程最大可以打開的文件數
worker_rlimit_nofile number; #更改worker線程中最大開放文件數量的限制。用于在不重新啟動主過程的情況下增加限制。默認為1024,但是1024太小了,所以我們可以設置為10240

[root@localhost ~]# cd /usr/local/nginx/conf/ [root@localhost conf]# vim nginx.conf1 2 user nginx nginx;3 worker_processes 1;4 worker_rlimit_nofile 10240; # #添加此行,并設置為10240,默認是1024 ·····省略部分········[root@localhost conf]# nginx -s reload # #重新加載配置文件立即生效

性能優化的配置參數
worker_processes n;
啟動worker線程個數,把進程進行切換就是上下文切換,(寄存器)記錄運行的位置,上下文切換的信息會一直被保存在CPU的內存中,直到被再次使用。

[root@localhost ~]# cd /usr/local/nginx/conf/ [root@localhost conf]# vim nginx.conf1 2 user nginx nginx;3 worker_processes 3; # 默認是1,更改就可以產生多個worker線程去處理4 worker_rlimit_nofile 10240;·····省略部分········[root@localhost conf]# nginx -s reload # 重新加載配置文件立即生效

將進程綁定到某cpu核心中,避免頻繁刷新緩存。綁定規則是核心數-1,比如總核心數為4,那么就綁定三個,另一個給其他使用
worker_cpu_affinity cpumask …;
#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核心

[root@localhost ~]# cd /usr/local/nginx/conf/ [root@localhost conf]# vim nginx.confuser nginx nginx;worker_processes 3;worker_rlimit_nofile 10240;worker_cpu_affinity 0001 0010 0100; # 添加此行,為前面增加的三個worker線程綁定三個核心 ·····省略部分········[root@localhost ~]# /usr/local/nginx/sbin/nginx -s stop;nginx # 重啟nginx ##查看是否生效: top命令,大寫L搜索nginx,然后按小寫f,移動到大寫P,然后空格選中,最后按q退出就可以看見是否生效


計時器解析度。降低此值,可減少gettimeofday()系統調用的次數。減少worker線程中的定時器分辨率,從而減少系統呼叫的數量。默認情況下,每次收到內核事件時都會被調用。隨著分辨率的降低,每個指定呼叫一次。
timer_resolution interval; (例如可以設置為 timer_resolution 100ms;)
指明worker進程的nice值,優先級是-20到19,指定的數字越小,優先級越高,相對優先級(可以調整) ,絕對優先級,100到139(無法調整) ,提高優先級可以先進行處理

worker_priority number; [root@localhost ~]# ps -elf|grep nginx # 查看發現worker線程的nice值是80,我們可以修改提高它的優先級,這樣就可以優先進行處理 1 S root 34284 1 0 80 0 - 20408 - 01:35 ? 00:00:00 nginx: master process nginx 5 S nginx 34285 34284 0 80 0 - 28560 do_epo 01:35 ? 00:00:00 nginx: worker process 5 S nginx 34286 34284 0 80 0 - 28560 do_epo 01:35 ? 00:00:00 nginx: worker process 5 S nginx 34287 34284 0 80 0 - 28560 do_epo 01:35 ? 00:00:00 nginx: worker process 0 S root 99205 33695 0 80 0 - 2302 - 01:53 pts/0 00:00:00 grep --color=auto nginx[root@localhost ~]# cd /usr/local/nginx/conf/ [root@localhost conf]# vim nginx.conf1 2 user nginx nginx;3 worker_processes 3;4 worker_rlimit_nofile 10240;5 worker_cpu_affinity 0001 0010 0100;6 worker_priority -20 # 添加此行來提高worker線程的優先級[root@localhost conf]# nginx -s reload # 發送信號重新加載配置文件立即生效 [root@localhost ~]# ps -elf|grep nginx # 查看發現worker線程的nice值提高為60 0 T root 78891 1460 0 80 0 - 11875 - 08:04 pts/0 00:00:00 vim /usr/local/nginx/conf/nginx.conf 1 S root 88430 1 0 80 0 - 20408 - 08:09 ? 00:00:00 nginx: master process nginx 5 S nginx 88431 88430 0 60 0 - 28556 do_epo 08:09 ? 00:00:00 nginx: worker process 5 S nginx 88432 88430 0 60 0 - 28556 do_epo 08:09 ? 00:00:00 nginx: worker process 5 S nginx 88433 88430 0 60 0 - 28556 do_epo 08:09 ? 00:00:00 nginx: worker process 0 S root 96763 1460 0 80 0 - 3087 - 08:13 pts/0 00:00:00 grep --color=auto nginx

事件相關的配置:event{}段中的參數配置
accept_mutex {off|on}; 互斥鎖,互相排斥,mster調度用戶請求至各worker進程時使用的負載均衡鎖;on表示能讓多個worker輪流地、序列化地去響應新請求 ,保持默認關閉的

accept_mutex {off|on}; lock_file logs/nginx.lock; # accept_mutex用到的互斥鎖鎖文件路徑(main段)

指明使用的事件模型,建議讓nginx自行選擇。指定要使用的連接處理。通常不需要明確說明,因為 nginx 默認情況下會使用最有效的方法

use [epoll | rtsig | select | poll];

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

[root@localhost conf]# vim nginx.conf ·····省略部分········events {worker_connections 20480; # 默認值是1024} ·····省略部分········# worker_connections 20480; 并發連接數 = 20480 * worker線程數量(3個)/2 # 使用ab命令測試并發,安裝工具 **yum -y install httpd-tools**[root@localhost ~]# ab -n 30000 http://192.168.240.60/ This is ApacheBench, Version 2.3 <$Revision: 1843412 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/Benchmarking 192.168.240.60 (be patient) Completed 3000 requests Completed 6000 requests Completed 9000 requests Completed 12000 requests Completed 15000 requests Completed 18000 requests Completed 21000 requests Completed 24000 requests Completed 27000 requests Completed 30000 requests Finished 30000 requestsServer Software: nginx/1.20.1 Server Hostname: 192.168.240.60 Server Port: 80Document Path: / Document Length: 612 bytesConcurrency Level: 1 Time taken for tests: 4.177 seconds Complete requests: 30000 Failed requests: 0 Total transferred: 25350000 bytes HTML transferred: 18360000 bytes Requests per second: 7182.64 [#/sec] (mean) Time per request: 0.139 [ms] (mean) Time per request: 0.139 [ms] (mean, across all concurrent requests) Transfer rate: 5927.08 [Kbytes/sec] receivedConnection Times (ms)min mean[+/-sd] median max Connect: 0 0 0.0 0 1 Processing: 0 0 0.1 0 3 Waiting: 0 0 0.1 0 3 Total: 0 0 0.1 0 3Percentage of the requests served within a certain time (ms)50% 066% 075% 080% 090% 095% 098% 099% 1100% 3 (longest request)

網絡連接相關的配置參數
長連接的超時時長,默認為65s

[root@localhost conf]# vim /usr/local/nginx/conf/nginx.conf ·····省略部分········#keepalive_timeout 0;keepalive_timeout 65; # 默認值#gzip on; ·····省略部分········

設置可以通過一個保持活力連接服務的最大請求數量。請求的最大數目后,連接將關閉。
定期關閉連接是每個連接內存分配的必要條件。因此,使用過高的最大請求量可能導致內存使用過量,不推薦
keepalive_requests number; (可以添加在http段,server段,location段)

[root@localhost]# cd /usr/local/nginx/conf [root@localhost conf]# vim nginx.conf ·····省略部分········server {listen 80;server_name localhost;keepalived_requests 10000 # 可以添加在server段#charset koi8-r; ·····省略部分········

常需要進行調整的參數
worker_processes # worker線程數量
worker_connections # 并發連接數
worker_cpu_affinity # cpu核心數綁定
worker_priority # worker線程的優先級
nginx作為web服務器時使用的配置:http{}段的配置參數
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;}} }

http{}段配置指令:
server {}:定義一個虛擬主機,示例如下:

server{ ? listen 81;(端口) ? server_name www.lp.com;(域名可以給多個) ? location / { ? root html/test; (網站位置) or alias /var/www/html/;(別名,別名一定要寫絕對路徑,就是把資源放到另外一個位置,當有人訪問時,看見的路徑是/根下面,其實我們已經放在了另一個位置,防止被攻擊) ? index index.html;? }

listen:指定監聽的地址和端口

listen address[:port]; listen port;

server_name NAME […]; 后面可跟多個主機,名稱可使用正則表達式或通配符
當有多個server時,匹配順序如下:

1.先做精確匹配檢查
2.左側通配符匹配檢查,如*.idfsoft.com
3.右側通配符匹配檢查,如mail.*
4.正則表達式匹配檢查,如~ ^.*.idfsoft.com$
5.default_server
root path; 設置資源路徑映射,用于指明請求的URL所對應的資源所在的文件系統上的起始路徑
alias path; 用于location配置段,定義路徑別名

index file; 默認主頁面

index index.php index.html;

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

[=code]:以指定的響應碼進行響應,而不是默認的原來的響應,默認表示以新資源的響應碼為其響應碼,例如 error_page 404 =200 /404_customed.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;

location區段,通過指定模式來與客戶端請求的URI相匹配
功能:允許根據用戶請求的URI來匹配定義的各location,匹配到時,此請求將被相應的location配置塊中的配置所處理,例如做訪問控制等功能

語法:location [ 修飾符 ] pattern {…}

沒有修飾符

[root@localhost local]# vim nginx/conf/nginx.conflocation / {root html;index index.html index.htm;}location /test {echo "test";}[root@localhost ~]# nginx -s reload[root@localhost ~]# curl http://192.168.240.60/test test [root@localhost ~]# curl http://192.168.240.60/test?sac test [root@localhost ~]# curl http://192.168.240.60/test?saccsac test

精確匹配

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation =/test {echo "test";}[root@localhost ~]# nginx -s reload##如下內容就可正確匹配 [root@localhost ~]# curl http://192.168.240.60/test test##如下內容則無法匹配 [root@localhost ~]# curl http://192.168.240.60/testd13 <html> <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.20.1</center> </body> </html>

正則表達式模式匹配(區分大小寫)

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf}location =~^/test {echo "test";}[root@localhost ~]# nginx -s reload ##如下內容就可正確匹配 [root@localhost ~]# curl http://192.168.240.60/test test##如下內容則無法匹配 [root@localhost ~]# curl http://192.168.240.60/test/ <html> <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.20.1</center> </body> </html>

正則表達式模式匹配(不區分大小寫)

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation = ~* ^/test {echo "test";}#error_page 404 /404.html;[root@localhost ~]# nginx -s reload[root@localhost ~]# curl http://192.168.240.60/tesT test##如下內容則無法匹配 [root@localhost ~]# curl http://192.168.240.60/test/ <html> <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.20.1</center> </body> </html>

~:類似于無修飾符的行為,也是以指定模式開始,不同的是,如果模式匹配,則停止搜索其他模式
優先級次序
( location = 路徑 ) --> ( location ^~ 路徑 ) --> ( location ~ 正則 ) --> ( location ~* 正則 ) --> ( location 路徑 )

查找順序和優先級:由高到底依次為
1.帶有=的精確匹配優先
2.正則表達式按照他們在配置文件中定義的順序
3.帶有^~修飾符的,開頭匹配
4.帶有*修飾符的,如果正則表達式與URI匹配
5.沒有修飾符的精確匹配

示例

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation / {root html;index index.html index.htm;}location /test {echo "test1";}location ~ ^ /test {echo "test2";}location ~* /test {echo "test2";}[root@localhost ~]# nginx -s reload

優先級測試

[root@localhost ~]# curl http://192.168.240.60/test test2 [root@localhost ~]# curl http://192.168.240.60/testid test1 [root@localhost ~]# curl http://192.168.240.60/TEST test3

https配置

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

修改nginx配置文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.con#server {listen 443 ssl;server_name localhost;ssl_certificate /etc/nginx/ssl/test.crt;ssl_certificate_key /etc/nginx/ssl/test.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@localhost ~]# nginx -s reload [root@localhost ~]# ss -antl State Recv-Q Send-Q Local Address:Port Peer Address:Port Process 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 [::]:*

訪問測試

訪問控制

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

在matser主機上修改nginx配置文件,將192.168.50.0網段禁止訪問

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conflocation / {root html;index index.html index.htm;allow 192.168.240.60/32;deny 192.168.240.50/32;} [root@localhost ~]# nginx -s reload

主機為192.168.240.60訪問

[root@localhost ~]# curl http://192.168.240.60 <!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>

主機為192.168.240.50訪問

[root@localhost ~]# curl http://192.168.240.60 <html> <head><title>403 Forbidden</title></head> <body> <center><h1>403 Forbidden</h1></center> <hr><center>nginx/1.20.1</center> </body> </html>

將deny字段改為all,表示在拒絕所有主機訪問

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf location / {root html;index index.html index.htm;allow 192.168.240.60/32;deny 192.168.240.50/32;deny all;} [root@localhost ~]# nginx -s reload

再次訪問

基于用戶認證

auth_basic "歡迎信息"; auth_basic_user_file "/path/to/user_auth_file";

user_auth_file內容格式為:

username:password

這里的密碼為加密后的密碼串,建議用htpasswd來創建此文件:

htpasswd -c -m /path/to/.user_auth_file USERNAME

示例

[root@localhost ~]# yum -y install httpd-tools[root@localhost ~]# htpasswd -c -m /usr/local/nginx/conf/.user-auth-file liu New password: Re-type new password: Adding password for user liu[root@localhost ~]# cat /usr/local/nginx/conf/.user-auth-file liu:$apr1$l0zw0VO6$.nC.ltsYIHDQSJ.nl/ySA0[root@localhost ~]# mkdir -p /usr/local/nginx/html/liu [root@localhost ~]# echo "welcome to xu!" > /usr/local/nginx/html/liu/index.html[root@localhost ~]# vim /usr/local/nginx/conf/nginx.confZZlocation / {root html;index index.htm;auth_basic "me liu!";auth_basic_user_file "/usr/local/nginx/conf/.user-auth-file";}[root@localhost ~]# 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@localhost ~]# nginx -s reload

開啟狀態界面

開啟status:

[root@localhost conf]# vim nginx.conflocation / {root html;index index.html index.htm;}location /status {stub_status;}[root@localhost conf]# nginx -s reload

狀態頁面信息詳解:

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

URL

HTML 統一資源定位器(Uniform Resource Locators)


URL 是一個網頁地址。

URL可以由字母組成,如"runoob.com",或互聯網協議(IP)地址: 192.68.20.50。大多數人進入網站使用網站域名來訪問,因為 名字比數字更容易記住。


URL - 統一資源定位器

Web瀏覽器通過URL從Web服務器請求頁面。

當您點擊 HTML 頁面中的某個鏈接時,對應的 標簽指向萬維網上的一個地址。

一個統一資源定位器(URL) 用于定位萬維網上的文檔。

一個網頁地址實例: http://www.runoob.com/html/html-tutorial.html 語法規則:

scheme://host.domain:port/path/filename

說明:

    • scheme - 定義因特網服務的類型。最常見的類型是 http
    • host - 定義域主機(http 的默認主機是 www)
    • domain - 定義因特網域名,比如 runoob.com
    • :port - 定義主機上的端口號(http 的默認端口號是 80)
    • path - 定義服務器上的路徑(如果省略,則文檔必須位于網站的根目錄中)。
    • filename - 定義文檔/資源的名稱

常見的 URL Scheme

以下是一些URL scheme:

Scheme訪問用于…
http超文本傳輸協議以 http:// 開頭的普通網頁。不加密。
https安全超文本傳輸協議安全網頁,加密所有信息交換。
ftp文件傳輸協議用于將文件下載或上傳至網站。
file您計算機上的文件。

rewrite

語法:rewrite regex replacement flag;,如:

[root@localhost conf]# ls ../html/qiang/ xin.jpg[root@localhost conf]# vim nginx.conflocation /liu {rewrite ^/liu/(.*\.jpg)$ /qiang/$1 break;}[root@localhost conf]# nginx -s reload

此處的$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

last

[root@localhost conf]# vim nginx.conflocation /liu {rewrite ^/liu/(.*\.html)$ /qiang/$1 last;}location /qiang {rewrite ^/qiang/(.*\.html)$ http://www.baidu.com last;} [root@localhost conf]# nginx -s reload #瀏覽器訪問IP/liu/qiang.html時結果為百度頁面

rewrite模塊的作用是用來執行URL重定向。這個機制有利于去掉惡意訪問的url,也有利于搜索引擎優化(SEO)

nginx使用的語法源于Perl兼容正則表達式(PCRE)庫,基本語法如下:

標識符意義
^必須以^后的實體開頭
$必須以$前的實體結尾
.匹配任意字符
[]匹配指定字符集內的任意字符
[^]匹配任何不包括在指定字符集內的任意字符串
|匹配 | 之前或之后的實體
()分組,組成一組用于匹配的實體,通常會有 | 來協助

捕獲子表達式,可以捕獲放在()之間的任何文本,比如:

^(hello|sir)$ //字符串為“hi sir”捕獲的結果:$1=hi$2=sir//這些被捕獲的數據,在后面就可以當變量一樣使用了

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.idfsoft.com;if ($invalid_referer) {rewrite ^/ http://www.idfsoft.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,如:

upstream idfsoft.com {ip_hash;server 127.0.0.1:9080 weight=5;server 127.0.0.1:8080 weight=5;server 127.0.0.1:1111; }

注意:這個方法本質還是輪詢,而且由于客戶端的ip可能是不斷變化的,比如動態ip,代理,翻墻等,因此ip_hash并不能完全保證同一個客戶端總是由同一個服務器來處理。

定義好upstream后,需要在server段內添加如下內容:

server {location / {proxy_pass http://idfsoft.com;} }

總結

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

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