- 隐藏 Nginx 版本号
- 修改 nginx 運作使用者-設定 nginx 的 cpu 親和力
- 設定 Nginx 每個程序最多可以打開的檔案數和事件處理模型
- ServerName 和 location 比對及高效傳輸模式
- Fastcgi 調優-gzip 壓縮網頁調優-expires 緩存調優
- 日志切割優化-目錄檔案通路控制-來源通路控制
- 禁止使用 IP 通路網站和 301 優化-防盜鍊-錯誤頁面的提示-開啟認證功能
- 修改 nginx 源代碼
- 下載下傳 nginx
- wget http://nginx.org/download/nginx-1.21.1.tar.gz
- 隐藏 Nginx 版本号,需要一共修改 3 個源代碼檔案 nginx.h ngx_http_header_filter_module.c ngx_http_special_response.c
-
tar xf nginx-1.21.1.tar.gz -C /opt/
cd /opt/nginx-1.21.1/
- vim src/core/nginx.h
-
改:
define NGINX_VERSION "1.21.1"
define NGINX_VER "nginx/" NGINX_VERSION
為:
#define NGINX_VERSION "8.8.8.8" #此行修改的是你想要的版本号。
#define NGINX_VER "GF/" NGINX_VERSION #此行修改的是你想修改的軟體名稱。
- 修改 HTTP 頭資訊中的 connection 字段,防止回顯具體版本号
- vim src/http/ngx_http_header_filter_module.c
- 改:static char ngx_http_server_string[] = "Server: nginx" CRLF;
- 為:static u_char ngx_http_server_string[] = "Server: GF" CRLF;
- 修改 ngx_http_special_response.c 檔案定義了 Nginx 報 404 錯誤時,不回顯版本号。
- vim src/http/ngx_http_special_response.c
-
改 :static u_char ngx_http_error_tail[] =
"<hr><center>nginx</center>" CRLF
"</body>" CRLF
"</html>
-
為:static u_char ngx_http_error_tail[] =
"<hr><center>GF</center>" CRLF
"</body>" CRLF
"</html>
- 編譯和安裝 nginx,安裝 nginx 依賴包
- yum -y install gcc gcc-c++ autoconf automake zlib zlib-devel openssl openssl-devel pcre pcre-devel gd-devel
-
建立一個 nginx 使用者用于後期啟動 nginx 程序使用,比直接使用 root 使用者啟動 nginx 更安全
useradd -s /sbin/nologin -M nginx
-
./configure --prefix=/usr/local/nginx1.21.1 --user=nginx --group=nginx \
--with-http_ssl_module --with-http_dav_module --with-http_stub_status_module \
--with-http_addition_module --with-http_sub_module --with-http_flv_module \
--with-http_mp4_module --with-http_realip_module --with-http_gzip_static_module \
--with-pcre --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log --with-debug --with-http_image_filter_module
-
--with-http_dav_module #啟用支援(增加 PUT,DELETE,MKCOL:建立集合,COPY 和MOVE 方法)。 預設關閉,需要編譯開啟
--with-http_stub_status_module #啟用支援(擷取 Nginx 上次啟動以來的工作狀态)。
--with-http_addition_module #啟用支援(作為一個輸出過濾器,支援不完全緩沖,分部分相應請求)。
--with-http_sub_module #啟用支援(允許一些其他文本替換 Nginx 相應中的一些文本)。
--with-http_flv_module #啟用支援(提供支援 flv 視訊檔案支援)。
--with-http_mp4_module #啟用支援(提供支援 mp4 視訊檔案支援,提供僞流媒體服務端支援)。
--with-pcre #支援 正規表達式
- 用#./configure --help 檢視幫助。
- make -j 4 && make install
-
啟動 nginx 服務
/usr/local/nginx/sbin/nginx
-
nginx systemctl 啟動腳本
-
# vim /lib/systemd/system/nginx.service
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx1.21.1/sbin/nginx
ExecReload=/usr/local/nginx1.21.1/sbin/nginx -s reload
ExecStop=/usr/local/nginx1.21.1/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
-
# systemctl daemon-reload
# systemctl enable nginx.service --now
# systemctl is-enabled nginx
enabled
- 測試 :檢視在 http 協定中是否隐藏了版本和軟體名
- 測試 :當通路時,出現 404 及其它錯誤時也會傳回已經隐藏的版本資訊
- 測試 :當通路時,出現 403 錯誤也會傳回已經隐藏的版本資訊
- 修改 Nginx 運作使用者
- vim /etc/nginx/nginx.conf
- 改為:user nginx;
- 不重新開機 nginx 服務加載配置檔案
- /usr/local/nginx1.21.1/sbin/nginx -s reload
- 這個是以 nginx 身份運作的 worker process 是 nginx 的工作程序,work 程序才為使用者提供服務
- 設定 Nginx 運作程序個數,一般設定為 CPU 核心數或者核心數的2倍,或者設定為 auto 自動識别
-
vim /etc/nginx/nginx.conf
worker_processes auto;
- 檢視 nginx 管理程序和 4 個 work 程序的父子關系
- pstree -p |grep nginx
- pstree 屬于 psmisc 包
- yum -y install psmisc
-
設定 Nginx 運作 CPU 的親和力
CPU 的親和力,就是把 nginx 每個程序綁定到固定的 cpu 上,進而減少 cpu 上下文切換導緻的額外的開銷。
比如伺服器是 4 核 4 線程的 cpu,配置如下:
vim /etc/nginx/nginx.conf
worker_processes auto; #在此行下添加
worker_cpu_affinity 0001 0010 0100 1000;
- 如果伺服器是 8 核 8 線程的 cpu,應該配置為如下:
- worker_processes 8;
- worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
-
檢視
# /usr/local/nginx1.21.1/sbin/nginx -s reload
# pstree -p |grep nginx
|-nginx(86539)-+-nginx(103390)
| |-nginx(103391)
| |-nginx(103393)
| `-nginx(103395)
# taskset -cp 103390
- list: 0 #表示 nginx PID 103390,隻能在第一個 cpu 運作,以此類推
-
設定 Nginx 每個程序最多可以打開的檔案數和事件處理模型
- Nginx 最多可以打開檔案數
-
worker_rlimit_nofile 655350;
這個指令是指當一個 Nginx 程序打開的最多檔案描述符數目,理論值應該是最多打開檔案數(ulimit -n)與 nginx 程序數相除,即:(ulimit -n)/ worker_processes ,但是 nginx 配置設定請求并不是那麼均勻,是以最好與 ulimit -n 的值保持一緻。
- 修改 ulimit -n 的值
- ulimit -n 655350
-
Nginx 事件處理模型
# vim /usr/local/nginx/conf/nginx.conf
events {
use epoll; #添加這一行,使用 epoll 模式
worker_connections 655350;
}
- Nginx 事件處理模型對比
select,poll,epoll 都是 nginx 下的 IO 多路複用的機制。I/O 多路複用就通過一種機制,可以監視多個描述符,一旦某個描述符就緒(一般是讀就緒或者寫就緒),能夠通知程式進行相應的讀寫操作。
Epoll 在 Linux2.6 核心中正式引入,和 select 和 poll 相似,其實都是 I/O 多路複用技術。
- epoll 優勢:
Epoll 沒有最大并發連接配接的限制,上限是最大可以打開檔案的數目,這個數字一般遠大于 2048, 一般來說這個數目和系統記憶體關系很大,具體數目可以 cat /proc/sys/fs/file-max 察看。
# cat /proc/sys/fs/file-max
808855
效率提升,Epoll 最大的優點就在于它隻管你“活躍”的連接配接,而跟連接配接總數無關,是以在實際的網絡環境中,Epoll 的效率就會遠遠高于 select 和 poll。
Epoll 在這點上使用了“共享記憶體”,更省記憶體,效率更高。
-
單個程序允許用戶端最大并發連接配接數
# 1 html vim /etc/nginx/nginx.conf
改:worker_connections 1024;
為:worker_connections 655350;
- worker_connections:這個屬性是指單個工作程序可以允許同時建立外部連接配接的數量。無論這個連接配接是外部主動建立的,還是内部建立的。一個工作程序建立一個連接配接後,程序将打開一個檔案副本。是以這個數量還受限于,作業系統 ulimit -n 設定的值和 nginx 的 worker_connections 的值。一般情況下系統 ulimit -n、worker_rlimit_nofile 、worker_connections 三者的值設定一緻。
- nginx 伺服器實際最大并發值就是:worker_processes*worker_connections 的乘積。
- # top -u nginx #Nginx 每個程序使用的記憶體大小。
-
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
104020 nginx 20 0 348828 275636 3148 S 0.0 3.4 0:00.37 nginx
104021 nginx 20 0 348828 275632 3144 S 0.0 3.4 0:00.35 nginx
104024 nginx 20 0 348828 275636 3148 S 0.0 3.4 0:00.36 nginx
104025 nginx 20 0 348828 275632 3144 S 0.0 3.4 0:00.36 nginx
- 注:通過檢視 RES 列,可以看到剛啟動的 nginx 程序占用記憶體大概 275M 左右。
-
ServerName 和 location 比對及高效傳輸模式
- ServerName 比對
-
ServerName 比對方式
(1)、精确比對:www.aa.com
(2)、左側通配符比對:*.aa.com
(3)、右側通配符比對:www.*
(4)、正規表達式:~ ^.*\.aa\.com$
(5)、default_server
(5)、服務 IP 位址
-
修改 server_name 值為實際的域名
# vim /etc/nginx/nginx.conf
改:server_name localhost;
為:server_name gf-beyond.com;
注:nginx 配置檔案中,每個參數都是以分号;結束
- -t #檢測 nginx 配置檔案是否正确
-
location 比對如下:
= 絕對比對。
^~ URL 前半部分比對,不檢查正則。~ 正則比對,區分大小寫。
~* 正則比對,不區分大小寫。
\ 轉義。
* 配置任意個任意字元。
$ 以什麼結尾。
例:比對出以.php 結尾的檔案且配置時不區分大小寫。
- location ~ \.php$ {..} #~ \.php$ 表示 url 中以.php 結尾的檔案且區分大小寫,都按{...}中的方法進行處理 。 這個就可以完成我們的需求。
-
例:比對出以.txt 結尾的檔案且配置時不區分大小寫
location ~* \.txt$ {
root file;
}
-
開啟高效傳輸模式
- 在 http 子產品内配置
-
http {
Include mime.types; #媒體類型。
default_type application/octet-stream; #預設媒體類型 足夠。
sendfile on; #開啟高效檔案傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出檔案,對于普通應用設為 on,如果用來進行下載下傳等應用磁盤 IO 重負載應用,可設定為 off,以平衡磁盤與網絡 I/O 處理速度,降低系統的負載。注意:如果圖檔顯示不正常把這個改成 off。
tcp_nopush on;必須在 sendfile 開啟模式才有效,防止網絡阻塞,積極的減少網絡封包段的數量。
-
連接配接逾時時間
主要目的是保護伺服器資源,CPU,記憶體,控制連接配接數,因為建立連接配接也是需要消耗資源的,TCP 的三次握手四次揮手等,我們一般斷掉的是那些建立連接配接但是不做事兒,也就是我建立了連結開始,但是後續的握手過程沒有進行,那麼我們的連結處于等待狀态的,全部斷掉!
同時我們也希望 php 建議短連結,消耗資源少。
-
keepalive_timeout 65; #在此行下加入如下
tcp_nodelay on;
client_header_timeout 15;
client_body_timeout 15;
send_timeout 15;
-
keepalived_timeout 用戶端連接配接保持會話逾時時間,超過這個時間,伺服器斷開這個連結。
tcp_nodelay;也是防止網絡阻塞,不過要包涵在 keepalived 參數才有效。client_header_timeout 用戶端請求頭讀取逾時時間,如果超過設個時間沒有發送任何資料,nginx将傳回 request time out 的錯誤。
client_body_timeout 用戶端求主體逾時時間,超過這個時間沒有發送任何資料,和上面一樣的錯誤提示。
send_timeout 響應用戶端逾時時間,這個逾時時間僅限于兩個活動之間的時間,如果超過這個時間,用戶端沒有任何活動,nginx 關閉連接配接。
- 檔案上傳大小限制 , PHP 可以修改上傳檔案大小限制,nginx 也可以修改。
- client_max_body_size 10m;
- Fastcgi 調優-gzip 壓縮網頁調優-expires 緩存調優
-
使用 gzip 壓縮功能,可能為我們節約帶寬,加快傳輸速度,有更好的體驗,節約成本,是以說這是一個重點。
Nginx 啟用壓縮功能需要 ngx_http_gzip_module 子產品,apache 使用的是 mod_deflate
一般需要壓縮的内容有:文本,js,html,css,對于圖檔,視訊,flash 什麼的不壓縮,同時也要注意,使用 gzip 的功能需要消耗 CPU
-
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 9;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml font/ttf font/otf
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_disable "MSIE [1-6]\.";
-
gzip on; #開啟壓縮功能。
gzip_min_length 1k; #設定允許壓縮的頁面最小位元組數,頁面位元組數從 header 頭的Content-Length(内容長度)中擷取,預設值是 0,不管頁面多大都進行壓縮,建議設定成大于 1K,如果小與 1K 可能會越壓越大。
gzip_buffers 4 32k; #壓縮緩沖區大小,表示申請 4 個機關為 32K 的記憶體作為壓縮結果流緩存,預設值是申請與原始資料大小相同的記憶體空間來存儲 gzip 壓縮結果。
gzip_http_version 1.1; #壓縮版本(預設 1.1,前端為 squid2.5 時使用 1.0)用于設定識别 HTTP協定版本,預設是 1.1,目前大部分浏覽器已經支援 GZIP 解壓,使用預設即可。
gzip_comp_level 9; #壓縮比例,用來指定 GZIP 壓縮比,1 壓縮比最小,處理速度最快,9 壓縮比最大,傳輸速度快,但是處理慢,也比較消耗 CPU 資源。
gzip_types text/css text/xml application/javascript; #用來指定壓縮的類型,‘text/html’類型總是會被壓縮。
gzip_vary on; #vary header 支援,該選項可以讓前端的緩存伺服器緩存經過 GZIP 壓縮的頁面,
例如用 Squid 緩存經過 nginx 壓縮的資料。
-
Fastcgi 相關概念
FastCGI 是一種協定,規定了 FastCGI 應用和支援 FastCGI 的 Web 伺服器之間的接口。Fastcgi 是靜态服務和動态服務的一個接口 FastCGI 是二進制連續傳遞的。
Fastcgi 相關的個概念如下:
Cache:寫入緩存區
Buffer:讀取緩存區
Fastcgi 是靜态服務和動态服務的一個接口
-
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_path /var/run/nginx-tmp-cache;
fastcgi_temp_file_write_size 128k;
fastcgi_cache_path /var/run/nginx-cache levels=1:2
keys_zone=ngx_fcgi_cache:512m inactive=1d max_size=40g;
- }
- 在 server 标簽添加如下:
- server {
- .......
-
location ~ .*\.(php|php5)?$ {
root /usr/local/nginx1.21.1/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
include fastcgi.conf;
fastcgi_cache ngx_fcgi_cache;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_key http://$host$request_uri;
}
.......
}
- fastcgi cache 資料 官方文檔:
http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache
配置詳解:
HTTP 字段:
fastcgi_connect_timeout 300; #指定連結到後端 FastCGI 的逾時時間。
fastcgi_send_timeout 300; # Nginx 允許 FastCGI 伺服器傳回資料的逾時時間,即在規定時間内後端伺服器必須傳完所有的資料,否則 Nginx 将斷開這個連接配接。
fastcgi_read_timeout 300; # Nginx 從 FastCGI 伺服器讀取響應資訊的逾時時間,表示連接配接建立成功後,Nginx 等待後端伺服器的響應時間。
fastcgi_buffers 4 64k; #指定緩沖區的數量和大小,如果一個 PHP 腳本傳回的頁面大小為 256K,則配置設定為 4 個 64K 的緩沖區來緩存,大于緩沖區大小的應答結果将被寫入 temp_file 臨時檔案中。推薦該值為你的站點 php 腳本傳回的頁面大小的平均進行設定,盡量不需要使緩存檔案寫入磁
盤,也不要設定太大導緻記憶體資源浪費。
fastcgi_temp_path /var/run/nginx-tmp-cache; #指定臨時目錄
fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=ngx_fcgi_cache:512m
inactive=1d max_size=40g; #定義緩存的路徑、大小、緩存時間。
上條指令詳解:(參數過長拆分詳解)
fastcgi_cache_path 建立緩存路徑,如果指定其他路徑需注意上層目錄是否建立。
levels:指定了該緩存空間有兩層 hash 目錄,設定緩存目錄層數,levels=1:2,表示建立兩層目錄緩存,最多建立三層。第一層目錄名取 fastcgi_cache_key md5 的最後一個字元,第二層目錄名取倒數2-3 字元,如:fastcgi_cache_key md5 為 b7f54b2df7773722d382f4809d65029c,則:
注:levels 雖然可以設定 3 層但是數值請勿大于 2.如果設定 1:2:3 則報錯。1:2:2 則正常。
levels=2:2 為/var/run/nginx-cache/9c/02/b7f54b2df7773722d382f4809d65029c
levels=1:2 為/var/run/nginx-cache/c/29/b7f54b2df7773722d382f4809d65029c
keys_zone 為這個緩存區起名為 zone_name
512m 指緩存空間最一開始為 512MB;
inactive=1d 代表如果緩存檔案一天内沒有被通路,則删除;
max_size=40g 代表緩存最大為 40G,建議根據自己的磁盤剩餘空間來寫大小,不能超過剩餘緩存的 80%;
Server 字段中配置詳解:
include fastcgi.conf; #引用 fastcgi 預設配置檔案
fastcgi_cache ngx_fcgi_cache; #指定緩存名稱,由 http 字段中 fastcgi_cache_path
建立。
fastcgi_cache_valid 200 302 1h; #設定 200、302 狀态的 URL 緩存 1 小時
fastcgi_cache_valid 301 1d; #設定 301 狀态的 URL 緩存 1 天。
fastcgi_cache_valid any 1m; #将其他應答緩存為 1 分鐘。
fastcgi_cache_min_uses 1; #設定請求 1 次就會被緩存。
fastcgi_cache_use_stale error timeout invalid_header http_500; #設定 500 狀态碼
不進行緩存。500 狀态碼意思是:内部伺服器錯誤
fastcgi_cache_key http://$host$request_uri; #該指令用來設定 Web 緩存的 Key 值,Nginx
根據 Key 值 MD5 緩存。一般根據 host(域名),request_uri(請求的路徑)等變量組合成
fastcgi_cache_key。MD5 值将作為緩存檔案名。
-
expires 緩存調優
緩存,主要針對于圖檔,css,js 等元素更改機會比較少的情況下使用,特别是圖檔,占用帶寬大,完全可以設定圖檔在浏覽器本地緩存 365d,css,js,html 可以緩存個 10 來天,這樣使用者第一次打開加載慢一點,第二次,就非常快了!緩存的時候,我們需要将需要緩存的拓展名列出來!
- Expires 緩存配置在 server 字段裡面:
-
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
expires 365d;
}
location ~ .*\.(js|css)?$ {
expires 30d;
}
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
expires 360d;
}
location ~(robots.txt) {
expires 7d;
break;
}
- }
-
expire 功能缺點:
被緩存的頁面或資料更新了,使用者看到的可能還是舊的内容,反而影響使用者體驗。
解決辦法:
第一個 縮短緩存時間,例如:1 天,不徹底,除非更新頻率大于 1 天。
第二個 對緩存的對象改名。
a.圖檔,附件一般不會被使用者修改,如果使用者修改了,實際上也是更改檔案名重新傳了而已。
b.網站更新對于 js,css 元素,一般可以改名,把 css,js,推送到 CDN。
網站不希望被緩存的内容:
1)廣告圖檔
2)網站流量統計工具
3)更新頻繁的檔案(google 的 logo)
- 檢視緩存目錄
- 将緩存檔案挂載至記憶體
-
# vim /etc/fstab #添加一行
tmpfs /var/run/nginx-cache tmpfs defaults,size=512M 0 0
mount -a
df -Th
- 注:fastcgi_cache 緩存是先寫在 fastcgi_temp_path 再移到 fastcgi_cache_path,是以如果不選擇将緩存目錄挂載至記憶體,建議 tmp_path 和 cache_path 在同一分區中,同分區檔案複制不會占用過高的 IO 資源。
- 浏覽器 F12 檢視緩存情況
-
日志切割優化-目錄檔案通路控制-來源通路控制
- 日志優化的目的,是為了一天日志一壓縮,按天存放,超過 10 天的删除。
- # vim /usr/local/nginx1.21.1/logs/cut_nginx_log.sh #每天日志分割腳本。
-
#!/bin/bash
date=$(date +%F -d -1day)
cd /var/log/nginx/
if [ ! -d cut ] ; then mkdir cut
fi
mv access.log cut/access_$(date +%F -d -1day).log
mv error.log cut/error_$(date +%F -d -1day).log
/usr/local/nginx1.21.1/sbin/nginx -s reload
tar -JcPf cut/$date.tar.xz cut/*
mv cut/$date.tar.xz /var/log/nginx/
rm -f cut/access* && rm -f cut/error*
if [[ -z `egrep -v "00 00 * * * /bin/bash /usr/local/nginx1.21.1/logs/cut_nginx_log.sh &> /dev/null" /var/spool/cron/root` ]]; then
echo "00 00 * * * /bin/bash /usr/local/nginx1.21.1/logs/cut_nginx_log.sh &> /dev/null" >> /var/spool/cron/root
fi
find /var/log/nginx/cut/ -type f -mtime +10 | xargs rm -rf
- chmod +x cut_nginx_log.sh
- ./cut_nginx_log.sh
-
健康檢查的日志,不用輸入到 log 中,因為這些日志沒有意義,我們分析的話隻需要分析通路日志,看看一些頁面連結,如 200,301,404 的狀态碼,在 SEO 中很重要,而且我們統計 PV 是頁面計算,這些都沒有意義,反而消耗了磁盤 IO,降低了伺服器性能,可以屏蔽這些如圖檔,js,css 這些不宜變化的内容。
# vim /etc/nginx/nginx.conf
- server {
-
......
location ~ .*\.(js|jpg|jpeg|JPG|JPEG|css|bmp|gif|GIF)$ {
access_log off;
}
- ........
- }
- 測試讀取日志檔案
- 日志目錄權限優化:隻允許root使用者有更改權限
- chown -R root. /var/log/nginx/
-
日志格式優化
- 注意不能寫在 server 字段 否則會報一個類似:nginx: [emerg] “log_format” directive is not allowed here in的錯誤
-
log_format access '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" $http_x_forwarded_for ' '"$upstream_addr" "$upstream_status" "$upstream_response_time" "$request_time"';
其中,各個字段的含義如下:
1. $remote_addr 與$http_x_forwarded_for 用以記錄用戶端的 ip 位址;
2. $remote_user :用來記錄用戶端使用者名稱;
3. $time_local : 用來記錄通路時間與時區;
4. request : 用來記錄請求的 url 與 http 協定;
5. status : 用來記錄請求狀态,功是 200;
6. body_bytes_s ent :記錄發送給用戶端檔案主體内容大小;
7. http_referer :用來記錄從哪個頁面連結通路過來的;
8. http_user_agent :記錄用戶端浏覽器的相關資訊;
-
目錄檔案通路控制
主要用在禁止目錄下指定檔案被通路,當然也可以禁止所有檔案被通路!一般什麼情況下用?比如是有存儲共享,這些檔案本來都隻是一些下載下傳資源檔案,那麼這些資源檔案就不允許被執行,如 sh,py,pl,php等等。
例如:禁止通路 images 下面的 php 程式檔案
- 在 server 字段添加
- server {
- ......
-
location ~ ^/images/(jpg|png)/.*\.(php|php5|.sh|.py|.py)$ {
deny all;
}
- }
- echo "<?php phpinfo(); ?>" > /usr/local/nginx1.21.1/html/images/test.php
- chown root. /usr/local/nginx1.21.1/html/images/test.php
- chmod 600 /usr/local/nginx1.21.1/html/images/test.php
- 其他檔案通路正常
- images 下的其他目錄下的 PHP 檔案
- 配置 nginx 禁止通路*.txt 檔案
- server {
- .................
-
location ~* \.(txt|doc)$ {
if ( -f $request_filename) {
root /usr/local/nginx1.21.1/html;
break;
}
deny all;
}
- ....................
- }
- 其他目錄
- 也可以重定向到某一個 URL
- server {
-
..........
location ~* \.(txt|doc)$ {
if ( -f $request_filename) {
root /usr/local/nginx1.21.1/html;
rewrite ^/(.*)$ http://www.gf-beyond.com last;
break;
}
#deny all;
}
......
}
- 對目錄進行限制的方法
-
server {
........
location ~ ^/(upload)/ {
deny all;
}
location ~ ^/(test)/ {
deny all;
}
........
}
-
來源通路控制
需要 ngx_http_access_module 子產品支援
-
server {
.......
location / {
root /usr/local/nginx1.21.1/html;
index index.html index.htm;
allow 192.168.1.0/24;
deny all;
}
.........
}
- 這裡為了測試改成 1.0 網段,本地使用 2.0 網段
-
禁止使用 IP 通路網站和 301 優化-防盜鍊-錯誤頁面的提示開啟認證功能
- 有時候,通路網站的時候,使用 IP 也可以,把這一層給屏蔽掉,讓其直接回報給 403,也可以做跳轉。
- 禁止 IP 直接通路,跳轉到首頁
-
server {
...............
listen 80;
server_name www.gf-beyond.com gf-beyond.com;
if ( $host = '192.168.2.40' ) {
rewrite ^/(.*)$ http://www.gf-beyond.com/$1 permanent;
}
......................
}
- 檢視日志 304 跳轉
- 域名跳轉的做法:
-
server {
listen 80;
server_name gf-beyond.com;
rewrite ^ http://www.baidu.com$request_uri?;
........
}
- 通路 http://www.gf-beyond.com 會直接跳轉到 baidu.com
-
403 回報的做法
server {
listen 80 default_server;
server_name _;
return 403;
........
}
- 通路 gf-beyond.com 會跳轉到 http://www.gf-beyond.com
-
防盜鍊
-
防止别人直接從你網站引用圖檔等連結,消耗了你的資源和網絡流量,那麼我們的解決辦法由幾種:
1:水印,品牌宣傳,你的帶寬,伺服器足夠
2:防火牆,直接控制,前提是你知道 IP 來源
3:防盜鍊政策
下面的方法是直接給予 404 的錯誤提示:
-
server {
.......
location ~* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
valid_referers none blocked *.gf-beyond.com gf-beyond.com;
if ($invalid_referer) {
return 404;
}
}
........
}
- 在圖檔上右鍵 --- 在新标簽頁打開圖檔
-
同時,我們也可以設定一個獨有的,圖檔比較小的,來做 rewrite 跳轉
server {
.........
location ~* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
valid_referers none blocked *.beyond.com beyond.com;
if ($invalid_referer) {
rewrite ^/ http://www.gf-beyond.com/images/nolink.png;
}
}
....
}
-
錯誤頁面的提示
- 對于自定義的錯誤頁面,我們隻需要将 errorpage 寫入到配置檔案。
-
server {
........
error_page 404 /404.html;
...............
}
- 開啟認證功能
-
server {
.............
location ~ /test/ {
auth_basic "gf";
auth_basic_user_file /usr/local/nginx1.21.1/passwd;
}
........................
}
-
htpasswd -cb /usr/local/nginx1.21.1/passwd gf 123456
chmod 400 /usr/local/nginx1.21.1/passwd
chown nginx. /usr/local/nginx1.21.1/passwd
nginx -s reload
-
防止 DDOS 攻擊
通過使用 limit_conn_zone 進行控制單個 IP 或者域名的通路次數。
- vim /etc/nginx/nginx.conf
-
http {
.......
limit_conn_zone $binary_remote_addr zone=addr:10m;
........
}
server {
...................
location / {
root /usr/local/nginx1.21.1/html;
index index.html index.htm;
allow 192.168.2.0/24;
deny all;
limit_conn addr 1;
}
...................
}
- 測試
- 在另外一台機器上
- ab -n 2 -c 2 -t 1 http://192.168.2.40/test/11.html
- 測試 -n 發出 2個 在 -t 1秒内并發 -c 2個請求
- 檢視 192.168.2.40 的通路日志
- 加大測試次數
- ab -n 200 -c 200 -t 1 http://192.168.2.40/1.html
- 檢視日志
-
server {
.......
location / {
root /usr/local/nginx1.21.1/html;
index index.html index.htm;
allow 192.168.2.0/24;
deny all;
limit_conn addr 1;
set $no_cache 0;
if ($request_method = POST) {
set $no_cache 1;
}
if ($query_string != "") {
set $no_cache 1;
}
if ($request_uri ~* "(/zb_system/)") {
set $no_cache 1;
}
fastcgi_cache_bypass $no_cache;
fastcgi_no_cache $no_cache;
}
.........
}
- 再次測試
-
完整 配置檔案内容
-
grep -Ev "^$|^#|^[[:space:]].*#.*$" /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_cpu_affinity 0001 0010 0100 1000;
worker_rlimit_nofile 655350;
events {
use epoll;
worker_connections 655350;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
tcp_nodelay on;
client_header_timeout 15;
client_body_timeout 15;
send_timeout 15;
client_max_body_size 10m;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 9;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml font/ttf font/otf application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_disable "MSIE [1-6]\.";
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_path /var/run/nginx-tmp-cache;
fastcgi_temp_file_write_size 128k;
fastcgi_cache_path /var/run/nginx-cache levels=1:2
keys_zone=ngx_fcgi_cache:512m inactive=1d max_size=40g;
log_format access '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" $http_x_forwarded_for ' '"$upstream_addr" "$upstream_status" "$upstream_response_time" "$request_time"';
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
listen 80;
server_name www.gf-beyond.com gf-beyond.com;
charset utf-8;
if ( $host = 'gf-beyond.com' ) {
rewrite ^/(.*)$ http://www.gf-beyond.com/$1 permanent;
}
if ( $host = '192.168.2.40' ) {
rewrite ^/(.*)$ http://www.gf-beyond.com/$1 permanent;
}
location ~* .*\.(js|css|jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar|mp4|rm|rmvb|mkv|gz)$ {
expires 360d;
valid_referers none blocked *.gf-beyond.com gf-beyond.com;
if ($invalid_referer) {
rewrite ^/ http://www.gf-beyond.com/images/nolink.png;
}
}
location ~* ^/(images|fonts|javascript|css|js|flash|media|static|assets)/ {
expires 360d;
}
location ~(robots.txt) {
expires 7d;
break;
}
location ~ .*\.(js|jpg|jpeg|JPG|JPEG|css|bmp|gif|GIF)$ {
access_log off;
}
location / {
root /usr/local/nginx1.21.1/html;
index index.html index.htm;
allow 192.168.2.0/24;
deny all;
limit_conn addr 1;
set $no_cache 0;
if ($request_method = POST) {
set $no_cache 1;
}
if ($query_string != "") {
set $no_cache 1;
}
if ($request_uri ~* "(/)") {
set $no_cache 1;
}
fastcgi_cache_bypass $no_cache;
fastcgi_no_cache $no_cache;
}
location ~* ^/images/(jpg|png)/.*\.(php|php5|.sh|.py|.pl)$ {
deny all;
}
location ~* \.(txt|doc)$ {
if ( -f $request_filename) {
root /usr/local/nginx1.21.1/html;
rewrite ^/(.*)$ http://www.gf-beyond.com last;
break;
}
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~ .*\.(php|php5)?$ {
root /usr/local/nginx1.21.1/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
include fastcgi.conf;
fastcgi_cache ngx_fcgi_cache;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_key http://$host$request_uri;
}
location ~ /test/ {
auth_basic "gf";
auth_basic_user_file /usr/local/nginx1.21.1/passwd;
}
}
}
- 切割日志腳本
-
cut_nginx_log.sh
#!/bin/bash
#
if [[ `id -u` != "0" ]]; then
echo "Must by root !";
exit 1;
fi
date=$(date +%F -d -1day)
logdir=/var/log/nginx
if [[ ! -d $logdir ]]; then
echo "Log Dir is not found !"
exit 2;
elif [[ ! -d $logdir/cut ]] ; then
mkdir $logdir/cut &> /dev/null
fi
cd $logdir
mv access.log cut/access_$date.log
mv error.log cut/error_$date.log
/usr/local/nginx1.21.1/sbin/nginx -s reload
if [[ -n $logdir/cut/$date.tar.xz ]]; then
tar -JcPf $logdir/$date.tar.xz cut/*
fi
rm -f cut/*.log
if [[ -z `egrep -v "00 00 * * * /bin/bash /usr/local/nginx1.21.1/logs/cut_nginx_log.sh &> /dev/null" /var/spool/cron/root` ]]; then
echo "00 00 * * * /bin/bash /usr/local/nginx1.21.1/logs/cut_nginx_log.sh &> /dev/null" >> /var/spool/cron/root
fi
find $logdir -type f -mtime +7 | xargs rm -rf {}