小白入門學(xué)習(xí)Nginx代理服務(wù)器?看這篇最新Nginx進(jìn)階學(xué)習(xí)最佳配置實(shí)踐指南就OK了
前置基礎(chǔ)知識學(xué)習(xí)
-
1.Nginx基礎(chǔ)安裝與配置詳細(xì) https://blog.weiyigeek.top/2019/9-1-121.html
-
2.Nginx進(jìn)階學(xué)習(xí)之最佳配置實(shí)踐指南 https://blog.weiyigeek.top/2019/9-1-124.html
-
3.Nginx模塊學(xué)習(xí)使用實(shí)踐指南 https://blog.weiyigeek.top/2021/3-1-633.html
-
4.Nginx安全加固與性能調(diào)優(yōu)最佳指南 https://blog.weiyigeek.top/2019/9-2-122.html
-
5.Nginx常遇問題入坑出坑整理 https://blog.weiyigeek.top/2020/9-2-622.html
0x00 編譯實(shí)踐
描述:在企業(yè)線上生產(chǎn)環(huán)境中推薦進(jìn)行Nginx編譯安裝,可以按照業(yè)務(wù)側(cè)重點(diǎn)進(jìn)行相應(yīng) Nginx 編譯參數(shù)配置,所以編譯參數(shù)不是功能加的越多越好,應(yīng)該盡可能少編譯模塊不用的最好不要加入,本小結(jié)將以最新的Nginx版本以及依賴版本進(jìn)行編譯演示。
Nginx-1.21.6+OpenSSL-1.1.1n
最新源碼構(gòu)建安裝整理,當(dāng)前最新版本nginx-1.21.6,實(shí)踐時(shí)間【2022年3月24日】
版本說明: pcre-8.45 、zlib-1.2.11、openssl-1.1.1n、nginx-1.21.6。
步驟 01.在從源代碼編譯 NGINX Open Source 之前,您需要為其依賴項(xiàng)安裝庫:
- PCRE – 支持正則表達(dá)式,NGINX Core 和 Rewrite 模塊需要。
# http://pcre.org/
# https://sourceforge.net/projects/pcre/files/
wget -c https://nchc.dl.sourceforge.net/project/pcre/pcre/8.45/pcre-8.45.tar.bz2
tar -jxf pcre-8.45.tar.bz2 && cd pcre-8.45
./configure
make && sudo make install
- zlib – 支持標(biāo)頭壓縮, NGINX Gzip 模塊需要。
# http://www.zlib.net/
wget -c http://zlib.net/zlib-1.2.11.tar.gz
tar -zxf zlib-1.2.11.tar.gz && cd zlib-1.2.11
./configure
make && sudo make install
- OpenSSL – 支持 HTTPS 協(xié)議, NGINX SSL 模塊和其他模塊需要。
# https://www.openssl.org/source/
wget -c http://www.openssl.org/source/openssl-1.1.1n.tar.gz
tar -zxf openssl-1.1.1n.tar.gz && cd openssl-1.1.1n
./config --prefix=/usr/local/openssl
make && sudo make install
# lib 庫加載到系統(tǒng)
echo "/usr/local/openssl/lib" >> /etc/ld.so.conf.d/libc.conf
ldconfig
# 可以看到當(dāng)下系統(tǒng)的Openssl版本已經(jīng)更新到最新
# root@weiyigeek-top:/usr/local/openssl/bin# openssl version
# OpenSSL 1.1.1n 15 Mar 2022
步驟 02.從 nginx.org 下載穩(wěn)定版和主線版本的源代碼文件,要下載并解壓最新主線版本的源代碼,請運(yùn)行:
# https://nginx.org
sudo mkdir -vp /usr/local/nginx/module /usr/lib/nginx/modules /var/cache/nginx/{client_temp,proxy_temp,fastcgi_temp,uwsgi_temp,scgi_temp}
wget https://nginx.org/download/nginx-1.21.6.tar.gz
tar zxf nginx-1.21.6.tar.gz && cd nginx-1.21.6
$ ./configure \
--prefix=/usr/local/nginx \
--with-pcre=../pcre-8.45 \
--with-zlib=../zlib-1.2.11 \
--user=ubuntu --group=ubuntu \
--sbin-path=/usr/sbin/nginx \
--conf-path=/usr/local/nginx/nginx.conf \
--pid-path=/usr/local/nginx/nginx.pid \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--lock-path=/var/run/nginx.lock \
--modules-path=/usr/lib/nginx/modules \
--http-client-body-temp-path=/var/cache/nginx/client_temp \
--http-proxy-temp-path=/var/cache/nginx/proxy_temp \
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
--http-scgi-temp-path=/var/cache/nginx/scgi_temp \
--with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-stream_geoip_module \
--with-threads --with-mail --with-mail_ssl_module \
--with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module \
--with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module \
--with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module \
--with-compat --with-file-aio \
--with-cc-opt='-Os -fomit-frame-pointer -g' --with-ld-opt=-Wl,--as-needed,-O1,--sort-common
# <!-- --add-dynamic-module=/usr/local/nginx/module -->
Tips :請注意 geoip_module 模塊, 如果需要使用則需要提前安裝好 GeoIP library,例如在Ubuntu系統(tǒng)上執(zhí)行apt-get install libgeoip-dev如下命令。
Tips : 請注意 通過yum或者apt安裝的nginx,通常會將nginx的配置文件放在/etc/nginx,而手動編譯構(gòu)建的一般是在 /usr/local/nginx 目錄中。
步驟 03.執(zhí)行./configure命令后的結(jié)果如下
Configuration summary
+ using threads
+ using PCRE library: ../pcre-8.45
+ using system OpenSSL library
+ using zlib library: ../zlib-1.2.11
nginx path prefix: "/usr/local/nginx"
nginx binary file: "/usr/sbin/nginx"
nginx modules path: "/usr/lib/nginx/modules"
nginx configuration prefix: "/usr/local/nginx"
nginx configuration file: "/usr/local/nginx/nginx.conf"
nginx pid file: "/usr/local/nginx/nginx.pid"
nginx error log file: "/var/log/nginx/error.log"
nginx http access log file: "/var/log/nginx/access.log"
nginx http client request body temporary files: "/var/cache/nginx/client_temp"
nginx http proxy temporary files: "/var/cache/nginx/proxy_temp"
nginx http fastcgi temporary files: "/var/cache/nginx/fastcgi_temp"
nginx http uwsgi temporary files: "/var/cache/nginx/uwsgi_temp"
nginx http scgi temporary files: "/var/cache/nginx/scgi_temp"
步驟 04.執(zhí)行構(gòu)建安裝后查看nginx版本以及構(gòu)建參數(shù)等信息
$ nginx -V
nginx version: nginx/1.21.6
built by gcc 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04)
built with OpenSSL 1.1.1n 15 Mar 2022
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-pcre=../pcre-8.45 --with-zlib=../zlib-1.2.11 --user=ubuntu --group=ubuntu --sbin-path=/usr/sbin/nginx --conf-path=/usr/local/nginx/nginx.conf --pid-path=/usr/local/nginx/nginx.pid --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --lock-path=/var/run/nginx.lock --modules-path=/usr/lib/nginx/modules --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-stream_geoip_module --with-threads --with-mail --with-mail_ssl_module --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-compat --with-file-aio --with-cc-opt='-Os -fomit-frame-pointer -g' --with-ld-opt=-Wl,--as-needed,-O1,--sort-common
步驟 05.執(zhí)行/usr/sbin/nginx命令, 啟用nginx服務(wù)并查看提供的服務(wù)。
# 查看Nginx并發(fā)進(jìn)程數(shù)
$ ps -ef | grep nginx | grep -v "grep" | wc -l
3
Nginx編譯(configure) 參數(shù)一覽
描述: 我們可以執(zhí)行./configure --help便可以查看編譯相關(guān)參數(shù)。
# 常用選項(xiàng) #
--prefix= #指向安裝目錄
--user= #指定程序運(yùn)行時(shí)的非特權(quán)用戶
--group= #指定程序運(yùn)行時(shí)的非特權(quán)用戶組
--with-perl= #設(shè)定perl庫文件路徑啟用pcre庫
--with-perl_modules_path= #設(shè)定perl模塊路徑
--with-pcre-opt= 在編譯時(shí)為pcre庫設(shè)置附加參數(shù)
--with-zlib= #指向zlib庫目錄
--with-zlib-opt= #在編譯時(shí)為zlib設(shè)置附加參數(shù)
--with-zlib-asm= #為指定的CPU使用zlib匯編源進(jìn)行優(yōu)化,CPU類型為pentium, pentiumpro
--with-openssl= #指向openssl安裝目錄
--with-openssl-opt #在編譯時(shí)為openssl設(shè)置附加參數(shù)
--with-http_ssl_module #啟用ngx_http_ssl_module支持(使支持https請求,需已安裝openssl)
--with-cc-opt= #設(shè)置C編譯器參數(shù)將被添加到CFLAGS變量(PCRE庫,需要指定–with-cc-opt=”-I /usr/local/include”,如果使用select()函數(shù)則需要同時(shí)增加文件描述符數(shù)量,可以通過–with-cc- opt=”-D FD_SETSIZE=2048”指定。)
--with-ld-opt= #設(shè)置連接文件參數(shù)鏈接系統(tǒng)庫。(PCRE庫,需要指定–with-ld-opt=”-L /usr/local/lib”。)
--with-cpu-opt= #指定編譯的CPU,可用的值為: pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64
#下面按需配置
--conf-path= #指向配置文件(nginx.conf)
--error-log-path= #指向錯(cuò)誤日志目錄
--pid-path= #指向pid文件(nginx.pid)
--sbin-path= #指向(執(zhí)行)程序文件(nginx)
--lock-path= #指向lock文件(nginx.lock)(安裝文件鎖定,防止安裝文件被別人利用,或自己誤操作。)
--builddir= #指向編譯目錄
#模塊添加
--with-rtsig_module #啟用rtsig模塊支持(實(shí)時(shí)信號)
--with-select_module #啟用select模塊支持(一種輪詢模式,不推薦在高載環(huán)境下使用)禁用:–without-select_module
--with-poll_module #啟用poll模塊支持(功能與select相同,與select特性相同,為一種輪詢模式,不推薦在高載環(huán)境下使用)
--with-file-aio #啟用file aio支持(一種APL文件傳輸格式)
--with-ipv6 #啟用ipv6支持
--with-http_realip_module #啟用ngx_http_realip_module支持(這個(gè)模塊允許從請求標(biāo)頭更改客戶端的IP地址值,默認(rèn)為關(guān))
--with-http_addition_module #啟用ngx_http_addition_module支持(作為一個(gè)輸出過濾器,支持不完全緩沖,分部分響應(yīng)請求)
--with-http_xslt_module #啟用ngx_http_xslt_module支持(過濾轉(zhuǎn)換XML請求)
--with-http_image_filter_module #啟用ngx_http_image_filter_module支持(傳輸JPEG/GIF/PNG 圖片的一個(gè)過濾器)(默認(rèn)為不啟用、gd庫要用到)
--with-http_geoip_module #啟用ngx_http_geoip_module支持(該模塊創(chuàng)建基于與MaxMind GeoIP二進(jìn)制文件相配的客戶端IP地址的ngx_http_geoip_module變量)
--with-http_sub_module #啟用ngx_http_sub_module支持(允許用一些其他文本替換nginx響應(yīng)中的一些文本)
--with-http_dav_module #啟用ngx_http_dav_module支持(增加PUT,DELETE,MKCOL:創(chuàng)建集合,COPY和MOVE方法)默認(rèn)情況下為關(guān)閉,需編譯開啟
--with-http_flv_module #啟用ngx_http_flv_module支持(提供尋求內(nèi)存使用基于時(shí)間的偏移量文件)
--with-http_gzip_static_module #啟用ngx_http_gzip_static_module支持(在線實(shí)時(shí)壓縮輸出數(shù)據(jù)流)
--with-http_random_index_module #啟用ngx_http_random_index_module支持(從目錄中隨機(jī)挑選一個(gè)目錄索引)
--with-http_secure_link_module #啟用ngx_http_secure_link_module支持(計(jì)算和檢查要求所需的安全鏈接網(wǎng)址)
--with-http_degradation_module #啟用ngx_http_degradation_module支持(允許在內(nèi)存不足的情況下返回204或444碼)
--with-http_stub_status_module #啟用ngx_http_stub_status_module支持(獲取nginx自上次啟動以來的工作狀態(tài))
--without-http_charset_module #禁用ngx_http_charset_module支持(重新編碼web頁面,但只能是一個(gè)方向–服務(wù)器端到客戶端,并且只有一個(gè)字節(jié)的編碼可以被重新編碼)
--without-http_gzip_module #禁用ngx_http_gzip_module支持(該模塊同-with-http_gzip_static_module功能一樣)
--without-http_ssi_module #禁用ngx_http_ssi_module支持(該模塊提供了一個(gè)在輸入端處理處理服務(wù)器包含文件(SSI)的過濾器,目前支持SSI命令的列表是不完整的)
--without-http_userid_module #禁用ngx_http_userid_module支持(該模塊用來處理用來確定客戶端后續(xù)請求的cookies)
--without-http_access_module #禁用ngx_http_access_module支持(該模塊提供了一個(gè)簡單的基于主機(jī)的訪問控制。允許/拒絕基于ip地址)
--without-http_auth_basic_module #禁用ngx_http_auth_basic_module(該模塊是可以使用用戶名和密碼基于http基本認(rèn)證方法來保護(hù)你的站點(diǎn)或其部分內(nèi)容)
--without-http_autoindex_module #禁用disable ngx_http_autoindex_module支持(該模塊用于自動生成目錄列表,只在ngx_http_index_module模塊未找到索引文件時(shí)發(fā)出請求。)
--without-http_geo_module #禁用ngx_http_geo_module支持(創(chuàng)建一些變量,其值依賴于客戶端的IP地址)
--without-http_map_module #禁用ngx_http_map_module支持(使用任意的鍵/值對設(shè)置配置變量)
--without-http_split_clients_module #禁用ngx_http_split_clients_module支持(該模塊用來基于某些條件劃分用戶。條件如:ip地址、報(bào)頭、cookies等等)
--without-http_referer_module #禁用disable ngx_http_referer_module支持(該模塊用來過濾請求,拒絕報(bào)頭中Referer值不正確的請求)
--without-http_rewrite_module #禁用ngx_http_rewrite_module支持(該模塊允許使用正則表達(dá)式改變URI,并且根據(jù)變量來轉(zhuǎn)向以及選擇配置。如果在server級 別設(shè)置該選項(xiàng),那么他們將在 location之前生效。如果在location還有更進(jìn)一步的重寫規(guī)則,location部分的規(guī)則依然會被執(zhí)行。如果這個(gè)URI重寫是因?yàn)?location部分的規(guī)則造成的,那么 location部分會再次被執(zhí)行作為新的URI。 這個(gè)循環(huán)會執(zhí)行10次,然后Nginx會返回一個(gè)500錯(cuò)誤。)
--without-http_proxy_module #禁用ngx_http_proxy_module支持(有關(guān)代理服務(wù)器)
--without-http_fastcgi_module #禁用ngx_http_fastcgi_module支持(該模塊允許Nginx 與FastCGI 進(jìn)程交互,并通過傳遞參數(shù)來控制FastCGI 進(jìn)程工作。 )FastCGI一個(gè)常駐型的公共網(wǎng)關(guān)接口。
--without-http_uwsgi_module #禁用ngx_http_uwsgi_module支持(該模塊用來醫(yī)用uwsgi協(xié)議,uWSGI服務(wù)器相關(guān))
--without-http_scgi_module #禁用ngx_http_scgi_module支持(該模塊用來啟用SCGI協(xié)議支持,SCGI協(xié)議是CGI協(xié)議的替代。它是一種應(yīng)用程序與HTTP服務(wù)接口標(biāo)準(zhǔn)。它有些像FastCGI但他的設(shè)計(jì) 更容易實(shí)現(xiàn)。)
--without-http_memcached_module #禁用ngx_http_memcached_module支持(該模塊用來提供簡單的緩存,以提高系統(tǒng)效率)
-without-http_limit_zone_module #禁用ngx_http_limit_zone_module支持(該模塊可以針對條件,進(jìn)行會話的并發(fā)連接數(shù)控制)
--without-http_limit_req_module #禁用ngx_http_limit_req_module支持(該模塊允許你對于一個(gè)地址進(jìn)行請求數(shù)量的限制用一個(gè)給定的session或一個(gè)特定的事件)
--without-http_empty_gif_module #禁用ngx_http_empty_gif_module支持(該模塊在內(nèi)存中常駐了一個(gè)1*1的透明GIF圖像,可以被非常快速的調(diào)用)
--without-http_browser_module #禁用ngx_http_browser_module支持(該模塊用來創(chuàng)建依賴于請求報(bào)頭的值。如果瀏覽器為modern ,則$modern_browser等于modern_browser_value指令分配的值;如 果瀏覽器為old,則$ancient_browser等于 ancient_browser_value指令分配的值;如果瀏覽器為 MSIE中的任意版本,則 $msie等于1)
--without-http_upstream_ip_hash_module #禁用ngx_http_upstream_ip_hash_module支持(該模塊用于簡單的負(fù)載均衡)
--with-http_perl_module #啟用ngx_http_perl_module支持(該模塊使nginx可以直接使用perl或通過ssi調(diào)用perl)
--http-log-path= # 設(shè)定access log路徑
--http-client-body-temp-path= # 設(shè)定http客戶端請求臨時(shí)文件路徑
--http-proxy-temp-path= # 設(shè)定http代理臨時(shí)文件路徑
--http-fastcgi-temp-path= # 設(shè)定http fastcgi臨時(shí)文件路徑
--http-uwsgi-temp-path= # 設(shè)定http uwsgi臨時(shí)文件路徑
--http-scgi-temp-path= # 設(shè)定http scgi臨時(shí)文件路徑
-without-http # 禁用http server功能
--without-http-cache # 禁用http cache功能
--with-mail #啟用POP3/IMAP4/SMTP代理模塊支持
--with-mail_ssl_module 啟用ngx_mail_ssl_module支持
--without-mail_pop3_module #禁用pop3協(xié)議(POP3即郵局協(xié)議的第3個(gè)版本,它是規(guī)定個(gè)人計(jì)算機(jī)如何連接到互聯(lián)網(wǎng)上的郵件服務(wù)器進(jìn)行收發(fā)郵件的協(xié)議。是因特網(wǎng)電子郵件的第一個(gè)離 線協(xié)議標(biāo) 準(zhǔn),POP3協(xié)議允許用戶從服務(wù)器上把郵件存儲到本地主機(jī)上,同時(shí)根據(jù)客戶端的操作刪除或保存在郵件服務(wù)器上的郵件。POP3協(xié)議是TCP/IP協(xié)議族中 的一員,主要用于 支持使用客戶端遠(yuǎn)程管理在服務(wù)器上的電子郵件)
--without-mail_imap_module #禁用imap協(xié)議(一種郵件獲取協(xié)議。它的主要作用是郵件客戶端可以通過這種協(xié)議從郵件服務(wù)器上獲取郵件的信息,下載郵件等。IMAP協(xié)議運(yùn)行在 TCP/IP協(xié)議之上, 使用的端口是143。它與POP3協(xié)議的主要區(qū)別是用戶可以不用把所有的郵件全部下載,可以通過客戶端直接對服務(wù)器上的郵件進(jìn)行操作。)
--without-mail_smtp_module #禁用smtp協(xié)議(SMTP即簡單郵件傳輸協(xié)議,它是一組用于由源地址到目的地址傳送郵件的規(guī)則,由它來控制信件的中轉(zhuǎn)方式。SMTP協(xié)議屬于 TCP/IP協(xié)議族,它幫助每臺計(jì)算機(jī)在發(fā)送或中轉(zhuǎn)信件時(shí)找到下一個(gè)目的地。)
--with-google_perftools_module #啟用ngx_google_perftools_module支持(調(diào)試用,剖析程序性能瓶頸)
--with-cpp_test_module #啟用ngx_cpp_test_module支持
--add-module= #啟用外部模塊支持
--with-cc= # 指向C編譯器路徑
--with-cpp= # 指向C預(yù)處理路徑
--without-pcre #禁用pcre庫
--with-md5= # 指向md5庫文件目錄(消息摘要算法第五版,用以提供消息的完整性保護(hù))
--with-md5-opt= # 在編譯時(shí)為md5庫設(shè)置附加參數(shù)
--with-md5-asm # 使用md5匯編源
--with-sha1= # 指向sha1庫目錄(數(shù)字簽名算法,主要用于數(shù)字簽名)
--with-sha1-opt= # 在編譯時(shí)為sha1庫設(shè)置附加參數(shù)
--with-sha1-asm # 使用sha1匯編源
--with-libatomic # 為原子內(nèi)存的更新操作的實(shí)現(xiàn)提供一個(gè)架構(gòu)
--with-libatomic= # 指向libatomic_ops安裝目錄
--with-debug # 啟用debug日志
Shell腳本一鍵部署虛擬主機(jī)(附上關(guān)鍵性腳本):
完整代碼:https://github.com/weiyigeek/SecOpsDev/Application/Web/Nginx/nginxVirtualHost-v1.sh
#!/bin/bash
#@Desc:Nginx多實(shí)例部署虛擬主機(jī)
#@Author:WeiyiGeek
#@CreatTime:2020年3月8日 12點(diǎn)06分
#@Site:WeiyiGeek.top
#@Test_Linux: Linux weiyigeek 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
#@release:CentOS Linux release 7.4.1708 (Core)
## Define nginx variable
NGX_VER=1.16.1
NGX_URI="http://nginx.org/download/nginx-${NGX_VER}.tar.gz"
NGX_SRC="nginx-${NGX_VER}.tar.gz"
NGX_NAME=${NGX_SRC%.tar.gz}
NGX_DIR="/usr/local/nginx/${NGX_VER}"
NGX_ARGS="--prefix=${NGX_DIR} --user=nginx --group=nginx --with-http_stub_status_module"
NGX_SRCCODE="${NGX_NAME}/src/core/nginx.h"
NGX_VHDIR="${NGX_DIR}/conf/domains"
## Define 防火墻開放端口
FIREWALL_PORT=(80 8080)
## [Nginx INSTALL]
function nginx_install(){
echo -e "\e[32m1.核查安裝依賴....... \e[0m"
CHECK_SOFT=$(rpm -qa | grep -cE "^gcc|^pcre|^zlib")
if [ $CHECK_SOFT -lt 2 ];then yum install -y gcc gcc-c++ pcre pcre-devel zlib-devel;fi
echo -e "\e[32m2.檢查nginx源碼包是否存在....... \e[0m"
if [ ! -f $NGX_SRC ];then wget -c $NGX_URI;fi
if [ ! -d $NGX_NAME ];then tar -zxf $NGX_SRC;fi
echo -e "\e[32m3.nginx安裝陸軍是否存在....... \e[0m"
if [ ! -f $NGX_DIR/sbin/nginx ];then mkdir -vp $NGX_DIR;fi
echo -e "\e[32m3.驗(yàn)證nginx用戶是否存在不存在則建立低權(quán)限用戶....... \e[0m"
CHECK_USER=$(getent passwd | grep -wc nginx)
if [ $CHECK_USER -eq 0 ];then useradd -s /sbin/nologin nginx -M; fi
echo -e "安全設(shè)置:Nginx版本隱藏......"
sed -i "s/$NGX_VER//g" $NGX_SRCCODE
sed -i 's/nginx\//JWS/g' $NGX_SRCCODE
sed -i 's/"NGINX"/"JWS"/g' $NGX_SRCCODE
echo -e "\e[32m4.進(jìn)行nginx預(yù)編譯及其編譯安裝....... \e[0m"
cd $NGX_NAME && ./configure $NGX_ARGS
if [ $? -eq 0 ];then
#進(jìn)行2個(gè)線程并行編譯(可以根據(jù)你處理器個(gè)數(shù)選擇)
make -j2 && make -j2 install
else
echo -e "\e[31m#Error: 預(yù)編譯失敗!終止安裝,請檢查軟件依賴! \e[0m"
exit
fi
if [ $? -ne 0 ];then echo -e "\e[31m#Error: 編譯安裝失敗!終止安裝 \e[0m";exit;fi
echo -e "\e[32m Nginx 成功安裝....... \n安裝目錄:${NGX_DIR} \n 正在啟動Nginx....\e[0m"
$NGX_DIR/sbin/nginx
}
## [Nginx CONFIG]
function nginx_vhost(){
NGX_VHOSTS=$1
firewall_config
cd ${NGX_DIR}
NGX_CNF="${NGX_DIR}/conf/nginx.conf"
if [ ! -f $NGX_CONF ];then echo -e "Nginx-配置文件不存在請仔細(xì)檢查!";exit;fi
#判斷是否已經(jīng)存在domains配置文件是則不同重新建立;
grep "domains" ${NGX_CNF} >>/dev/null 2>&1
if [ $? -ne 0 ];then
#備份NGX配置文件
cp ${NGX_CNF}{,_$(date +%F_%H%M%S).bak}
mkdir -vp ${NGX_VHDIR}
sed -i "s/#user nobody/user nginx/g" ${NGX_CNF}
sed -i "s/#gzip/gzip/g" ${NGX_CNF}
#去除空行以及注釋
grep -vE "#|^$" ${NGX_CNF} > ${NGX_CNF}.swp
#重點(diǎn)刪除server字符到文件末尾
sed -i '/server/,$d' ${NGX_CNF}.swp
cp ${NGX_CNF}.swp ${NGX_CNF}
echo -e " include domains/*;\n}" >> ${NGX_CNF}
fi
cat>${NGX_VHDIR}/$NGX_VHOSTS.conf<<EOF
server {
listen 80;
server_name $NGX_VHOSTS;
location / {
root html/$NGX_VHOSTS;
index index.html index.htm;
}
#Nginx 監(jiān)控模塊啟用
location /nginxStatus {
stub_status;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
EOF
echo -e "\e[32m$NGX_VHOSTS 網(wǎng)站目錄建立之中.....\e[0m"
if [ ! -d $NGX_DIR/html/$NGX_VHOSTS/ ];then
mkdir -vp $NGX_DIR/html/$NGX_VHOSTS/
cat>$NGX_DIR/html/$NGX_VHOSTS/index.html<<EOF
<h1>$NGX_VHOSTS Test Pages. </h1>
<p>By WeiyiGeek.top </p>
<hr color=red>
EOF
fi
echo -e "\e[32mNginx配置文件驗(yàn)證中.....\e[0m"
$NGX_DIR/sbin/nginx -t
if [ $? -ne 0 ];then
echo -e "\e[31mNginx配置文件有誤,請?zhí)幚礤e(cuò)誤后重啟Nginx服務(wù)器:\n ${NGX_DIR}/sbin/nginx -s reload"
fi
cat ${NGX_VHDIR}/$NGX_VHOSTS.conf
echo -e "\e[32mNginx重啟之中.....\e[0m"
$NGX_DIR/sbin/nginx -s reload
CHECK_STATUS=$(netstat -tlnp | grep -wc "nginx")
if [ $CHECK_STATUS -ne 0 ];then
echo -e "\e[32m#Nginx 啟動成功.... \e[0m"
else
echo -e "\e[31m#Nginx 啟動失敗.... \e[0m"
fi
}
運(yùn)行效果:

測試效果:

0x01 Nginx 配置最佳實(shí)踐
Nginx 之 多配置文件配置
描述: Nginx配置文件中支持包含多個(gè)配置文件,比如下面的虛擬主機(jī)的配置將使用,在程序加載運(yùn)行時(shí)候首先會讀取nginx.conf 的配置文件,然后再讀取 /etc/nginx/conf.d/下面的配置文件;
例如,我們需要在/etc/nginx/nginx.conf文件中,進(jìn)行如下設(shè)置include /etc/nginx/conf.d/*.conf;
http {
....
include conf.d/*.conf;
....
}

Nginx 之 Server 偵聽端口主機(jī)頭配置淺析
描述:常規(guī)網(wǎng)站編譯安裝后運(yùn)行只是單個(gè)網(wǎng)站訪問,我們?nèi)绾慰梢宰龅蕉嗑W(wǎng)站同時(shí)運(yùn)行到該Nginx服務(wù)器上,那我們便可使用Nginx提供的虛擬機(jī)主機(jī)方式, 使得一個(gè)服務(wù)端口可以訪問不同的服務(wù)應(yīng)用;
常規(guī)有三種方式:
-
- 多端口
-
- 多IP
-
- 多域名:虛擬主機(jī)(VirtualHost)
環(huán)境準(zhǔn)備:
cat >> /etc/hosts<<END
127.0.0.1 v1.weiyigeek.top v2.weiyigeek.top
END
流程步驟:
- 1.修改移除Nginx.conf配置文件中的
Server {...}包含的參數(shù)添加include domains/*;;
user nginx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
include domains/*;
}
- 2.在Nginx的Conf目錄中建立一個(gè)domains目錄(注意這里不要建立到上級目錄之中,否則會出現(xiàn)nginx master進(jìn)程已經(jīng)啟動但是無監(jiān)聽端口),進(jìn)入該目錄中建立虛擬主機(jī)v1.weiyigeek.top.conf文件
server {
listen 80;
server_name v1.weiyigeek.top; #關(guān)鍵點(diǎn)
location / {
#關(guān)鍵點(diǎn)
root html/v1.weiyigeek.top;
index index.html index.htm;
}
#Nginx 監(jiān)控模塊啟用
location /nginxStatus {
stub_status;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
- 3.在nginx安裝目錄中的html中建立一個(gè)與虛擬主機(jī)同名的文件夾(當(dāng)然名字您可以任意取,但是必須和v1.weiyigeek.top.conf中指定路與的root一致)
[root@WeiyiGeek html]# pwd
/usr/local/nginx/1.16.1/html
[root@WeiyiGeek html]# ls
50x.html index.html v1.weiyigeek.top v2.weiyigeek.top
配置示例
server {
# 使用標(biāo)準(zhǔn) HTTP 協(xié)議
listen 80;
# 使用標(biāo)準(zhǔn) HTTPS 協(xié)議
listen 443 ssl;
# 使用 http2 協(xié)議
listen 443 ssl http2;
# 使用IPV6地址監(jiān)聽80端口
listen [::]:80;
# 只使用IPV6地址監(jiān)聽80端口
listen [::]:80 ipv6only=on;
# 匹配指定域名訪問
server_name weiyigeek.top;
# 匹配多域名訪問
server_name weiyigeek.top www.weiyigeek.top;
# 匹配weiyigeek.top下所有子域名
server_name *.weiyigeek.top;
# 匹配所有的包含weiyigeek.top的頂級域名
server_name weiyigeek.top.*;
# 僅匹配IP地址訪問
server_name "";
server_name _;
}
溫馨提示: 當(dāng)網(wǎng)站設(shè)置支持http2以后可以從請求響應(yīng)頭中看到如下字段 X-Firefox-Spdy:h2

Nginx 之 Location 規(guī)則配置淺析
描述: Location 語法規(guī)則:location [=|~|~*|^~] /uri/ { … }
=: 表示精確匹配./: 表示通用匹配, 即任何請求都會匹配到。~: 表示區(qū)分大小寫的正則匹配.~*: 表示不區(qū)分大小寫的正則匹配.!~,!~*: 分別標(biāo)識為區(qū)分大小寫不匹配及不區(qū)分大小寫不匹配的正則^~: 表示URL以某個(gè)常規(guī)字符串開頭,可以理解為匹配url路徑即可,值得注意的是Nginx不對URL做編碼,例如會將請求為/static/20%/aa被^~ /static/ /aa規(guī)則匹配到。
默認(rèn)情況下 location 的匹配順序?yàn)?code>精確匹配 -> 開頭匹配(^~) -> 文件順序中的正則匹配 -> 通用匹配(/), 當(dāng)有匹配成功的URL則停止匹配。
例如,有如下匹配規(guī)則:
location = / {
#規(guī)則A.精確匹配 / URL 下的操作。
}
location = /login {
#規(guī)則B.精確匹配 /login URL 下的操作。
}
location ^~ /static/ {
#規(guī)則C.正則匹配 /static/ URL 下的操作。
}
location ~ \.(gif|jpg|png|svg|js|css)$ {
#規(guī)則D,注意:是根據(jù)括號內(nèi)的大小寫進(jìn)行匹配,括號內(nèi)全是小寫只匹配小寫。
}
location ~* \.(gif|jpg|png|svg|js|css)$ {
#規(guī)則D,注意:忽略大寫來匹配靜態(tài)資源后綴。
}
location ~* \.png$ {
#規(guī)則E.匹配以.png或者.PNG結(jié)尾的靜態(tài)資源。
}
location !~ \.xhtml$ {
#規(guī)則F.不匹配.xhtml為后綴的資源。
}
location !~* \.xhtml$ {
#規(guī)則G.不匹配.xhtml或者.XHTML為后綴的資源。
}
location / {
#規(guī)則H.通用匹配,當(dāng)上述匹配都不能匹配時(shí),使用該規(guī)則。
}
在實(shí)踐過程中常見, 有如下幾種匹配規(guī)則:
# 第一個(gè)必選規(guī)則是直接匹配網(wǎng)站根,通過域名訪問網(wǎng)站首頁比較頻繁,使用這個(gè)會加速處理,
# 這里可以是直接轉(zhuǎn)發(fā)給后端應(yīng)用服務(wù)器了,也可以是一個(gè)靜態(tài)首頁。
location = / {
root /usr/local/nginx/html
proxy_pass http://tomcat:8080/index
}
# 第二個(gè)必選規(guī)則是處理靜態(tài)文件請求,這是nginx作為http服務(wù)器的強(qiáng)項(xiàng)
# 有兩種配置模式,目錄匹配或后綴匹配,任選其一或搭配使用
location ^~ /static/ { # // 以xx開頭
root /webroot/static/; # 注意,需要指定跟目錄.
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ { # // 以xx結(jié)尾
root /webroot/res/;
}
#第三個(gè)規(guī)則就是通用規(guī)則,用來轉(zhuǎn)發(fā)動態(tài)請求到后端應(yīng)用服務(wù)器
#非靜態(tài)文件請求就默認(rèn)是動態(tài)請求,自己根據(jù)實(shí)際把握
location / {
proxy_pass http://tomcat:8080/
}
Nginx 之 規(guī)則判斷表達(dá)式淺析
Nginx 常用判斷表達(dá)式如下:
-f和!-f: 用來判斷是否存在文件-d和!-d:用來判斷是否存在目錄-e和!-e:用來判斷是否存在文件或目錄-x和!-x:用來判斷文件是否可執(zhí)行- 除此之外我們還可以使用上一小節(jié)的正則匹配符進(jìn)行判斷。
nginx 全局變量一覽:
arg_PARAMETER # 這個(gè)變量包含GET請求中,如果有變量PARAMETER時(shí)的值。
args # 這個(gè)變量等于請求行中(GET請求)的參數(shù),如:foo=123&bar=blahblah;
binary_remote_addr # 二進(jìn)制的客戶地址。
body_bytes_sent # 響應(yīng)時(shí)送出的body字節(jié)數(shù)數(shù)量。即使連接中斷,這個(gè)數(shù)據(jù)也是精確的。
content_length # 請求頭中的Content-length字段。
content_type # 請求頭中的Content-Type字段。
cookie_COOKIE # cookie COOKIE變量的值
document_root # 當(dāng)前請求在root指令中指定的值。
document_uri # 與uri相同。
host # 請求主機(jī)頭字段,否則為服務(wù)器名稱。
hostname # 設(shè)置為gethostname返回的機(jī)器主機(jī)名
http_HEADER # 請求header頭字段
is_args # 如果有args參數(shù),這個(gè)變量等于”?”,否則等于”",空值。
http_user_agent # 客戶端agent信息
http_cookie # 客戶端cookie信息
limit_rate # 這個(gè)變量可以限制連接速率。
query_string # 與args相同。
request_body_file #客戶端請求主體信息的臨時(shí)文件名。
request_method #客戶端請求的動作,通常為GET或POST。
remote_addr #客戶端的IP地址。
remote_port #客戶端的端口。
remote_user #已經(jīng)經(jīng)過Auth Basic Module驗(yàn)證的用戶名。
request_completion #如果請求結(jié)束,設(shè)置為OK. 當(dāng)請求未結(jié)束或如果該請求不是請求鏈串的最后一個(gè)時(shí),為空(Empty)。
request_method #GET或POST
request_filename #當(dāng)前請求的文件路徑,由root或alias指令與URI請求生成。
request_uri #包含請求參數(shù)的原始URI,不包含主機(jī)名,如:”/foo/bar.php?arg=baz”。不能修改。
scheme #HTTP方法(如http,https)。
server_protocol #請求使用的協(xié)議,通常是HTTP/1.0或HTTP/1.1。
server_addr #服務(wù)器地址,在完成一次系統(tǒng)調(diào)用后可以確定這個(gè)值。
server_name #服務(wù)器名稱。
server_port #請求到達(dá)服務(wù)器的端口號。
Nginx 解析URL用作判斷的全局變量,例如,訪問的URL為http://weiyigeek.top:8080/test1/test2/test.php.
$host:weiyigeek.top
$server_port:8080
$request_uri:http://weiyigeek.top:8080/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/data/nginx/html
$request_filename:/data/html/test1/test2/test.php
簡單示例:
- 1.判斷請求的靜態(tài)資源文件是否是存在的,如不存在則返回403.
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
return 403;
break;
}
}
- 2.判斷Nginx全局變量并進(jìn)行跳轉(zhuǎn)到指定頁面。
if ( $host !~* weiyigeek\.top ) {
return 301 https://space.bilibili.com/385802642;
}
- 3.文件反盜鏈并設(shè)置過期時(shí)間
location ~*^.+\.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {
valid_referers none blocked *.weiyigeek.top localhost 127.0.0.1;
if ($invalid_referer) {
rewrite ^/ https://weiyigeek.top/wechat.html;
return 412;
break;
}
root /usr/local/nginx/html
access_log off;
expires 3d;
break;
}
- 4.自定義變量判斷跳轉(zhuǎn)到指定頁面.
# 僅允許222.222.222.222或者內(nèi)網(wǎng)的兩個(gè)IP訪問,其他IP都rewrite到停服頁面
if ( $remote_addr = 222.222.222.222){set $my_ip 1;}
if ( $remote_addr = 192.168.1.170 ){ set $my_ip 1;}
if ( $remote_addr = 192.168.1.169 ){ set $my_ip 1;}
if ( $my_ip != 1) {rewrite ^/design/(.*)\.php$ /weiyigeek.html?$1&;} #將*.php轉(zhuǎn)到tingfu.html
溫馨提示: 此處以Nginx暴露給互聯(lián)網(wǎng), 所以利用 $remote_addr 變量獲取訪問者地址, 如果用了負(fù)載均衡的話此處應(yīng)該是$http_x_forwarded_for 變量。
Nginx 之 Redirect重定向與ReWrite重寫 配置淺析
Redirect(重定向)語法示例
# http 向 https 跳轉(zhuǎn) (永久)
server {
listen 80;
server_name weiyigeek.top www.weiyigeek.top;
return 301 https://$host$request_uri;
}
# http 向 https 跳轉(zhuǎn)(臨時(shí))
server {
listen 80;
server_name weiyigeek.top www.weiyigeek.top;
return 302 https://www.weiyigeek.top$request_uri;
}
ReWrite 重寫語法示例
rewrite 正則表達(dá)式以及其可用參數(shù):
last: 基本上都用這個(gè)Flag。break: 中止 Rewirte 不在繼續(xù)匹配redirect: 返回臨時(shí)重定向的HTTP狀態(tài)302permanent: 返回永久重定向的HTTP狀態(tài)301
# http 向 https 跳轉(zhuǎn)
server {
listen 80;
server_name weiyigeek.top www.weiyigeek.top;
# 判斷請求host是否是 www.weiyigeek.top ,如果是 weiyigeek.top 則重寫為 www.weiyigeek.top
if ($http_host !~ "^www\.weiyigeek\.top$" {
rewrite ^(.*) https://www.weiyigeek.top$1 permanent;
}
}
# 利用重寫規(guī)則防止盜鏈
location ~* \.(gif|jpg|png|svg|css|js)$ {
valid_referers none blocked *.weiyigeek.top localhost 127.0.0.1 server_names ~\.google\. ~\.baidu\.;
if ($invalid_referer) {
rewrite ^/ https://www.weiyigeek.top/403.jpg;
}
}
# 利用重寫功能可將網(wǎng)頁中舊的訪問目錄重寫到新的訪問路徑
# 例如, 如果訪問https://blogwww.weiyigeek.top/2020/10/515.html 則將顯示首頁。
if ( $document_uri ~* /([0-9]+)/([0-9]+)/([0-9]+)\.html$) {
rewrite ^/ /index.html last;
}
溫馨提示:301 與 302 狀態(tài)碼的不同區(qū)別。
- 301 redirect: 301 代表永久性轉(zhuǎn)移(
Permanently Moved) - 網(wǎng)站SEO推薦。 - 302 redirect: 302 代表暫時(shí)性轉(zhuǎn)移(
Temporarily Moved)
Nginx 之 SSL 證書安全配置淺析
描述: 通常為了保證網(wǎng)站數(shù)據(jù)在傳輸過程中不被竊取和篡改,我們需要為其配置SSL證書,而在Nginx中配置方法是非常的簡單的,不過最重要的還是你要生成私鑰以及證書申請文件csr向證書頒發(fā)機(jī)構(gòu)生成網(wǎng)站證書。
# Permanent Redirect for HTTP to HTTPS
server {
listen 80;
listen [::]:80;
server_name weiyigeek.top;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name weiyigeek.top;
# HSTS (ngx_http_headers_module is required) 應(yīng)該只使用 HTTPS 而不是使用 HTTP 通信
add_header Strict-Transport-Security "max-age=31536000;includeSubDomains;preload" always;
# XXS-Protection
add_header X-XSS-Protection "1; mode=block";
# MIME 模擬探測
add_header X-Content-Type-Options nosniff;
# Frame 安全控制
add_header X-Frame-Options ALLOW-FROM music.163.com;
# Spider Robots 爬取策略限制
add_header X-Robots-Tag none;
# 開啟 SSL ,如果想http 與 https 公用一個(gè)配置則可以將其注釋( the "ssl" directive is deprecated )
# ssl on;
# 配置證書鏈與證書密鑰
ssl_certificate /etc/nginx/ssl/fullchain.cer;
ssl_certificate_key /etc/nginx/ssl/weiyigeek.top.key;
# ssl會話復(fù)用超時(shí)時(shí)間以及會話復(fù)用緩存大小
ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m; # about 40000 sessions
# 配置雙證書時(shí)開啟否則應(yīng)該關(guān)閉
ssl_session_tickets off;
## OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
# 使用根 CA 和中間證書驗(yàn)證 OCSP 響應(yīng)的信任鏈
ssl_trusted_certificate /etc/nginx/ssl/ca.cer;
# 僅使用ECDH是不用配置ssl_dhparam的否則你應(yīng)該為它配置上
# curl https://ssl-config.mozilla.org/ffdhe2048.txt > /path/to/dhparam
ssl_dhparam /path/to/dhparam;
# 兼容性較為通用的SSL協(xié)議與加密算法套件
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE:ECDH:AES:HIGH:EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:!NULL:!aNULL:!eNULL:!EXPORT:!PSK:!ADH:!DH:!DES:!MD5:!RC4;
# 安全配置: ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE;
# 證書常規(guī)握手加密算法方式共十八個(gè),ECDHE、DHE、AES開頭分別6個(gè)
; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:HIGH:!NULL:!aNULL:!eNULL:!EXPORT:!PSK:!ADH:!DES:!MD5:!RC4;
# 為了兼容性推薦服務(wù)器自動選擇要使用的算法套件
ssl_prefer_server_ciphers on;
# replace with the IP address of your resolver
resolver 223.6.6.6 8.8.8.8 192.168.12.254;
}
補(bǔ)充說明: 為Nginx服務(wù)器配置RSA與ECDSA雙證書的兩種方式。
# 1.首先是將兩個(gè)證書鏈都加入 Nginx 的配置文件
ssl_certificate example.com.rsa.crt;
ssl_certificate_key example.com.rsa.key;
ssl_certificate example.com.ecdsa.crt;
ssl_certificate_key example.com.ecdsa.key;
# 2.或者使用 CT 的話有兩種方法,一個(gè)是將兩個(gè)證書的 CT 信息放到同一目錄,并做如下設(shè)置,Nginx CT 模塊會自動在這個(gè)目錄下查找相應(yīng)證書的 CT 信息并發(fā)送驗(yàn)證:
ssl_ct on;
ssl_ct_static_scts /path/to/sct/dir;
# 我們也可以單獨(dú)配置每個(gè)證書的 CT 文件
ssl_ct on;
ssl_certificate example.com.rsa.crt;
ssl_certificate_key example.com.rsa.key;
ssl_ct_static_scts xample.com.rsa.scts;
ssl_certificate example.com.ecdsa.crt;
ssl_certificate_key example.com.ecdsa.key;
ssl_ct_static_scts example.com.ecdsa.scts;
Nginx 之 資源壓縮配置淺析
描述: 為了降低服務(wù)器帶寬壓力以及優(yōu)化響應(yīng)速度, 通常我們需要在Nginx服務(wù)器配置中為其開啟gzip壓縮,
配置示例:
# 開啟gzip
gzip on;
# 啟用gzip壓縮的最小文件,小于設(shè)置值的文件將不會壓縮
gzip_min_length 2k;
# gzip 壓縮級別,1-10,數(shù)字越大壓縮的越好,也越占用CPU時(shí)間,后面會有詳細(xì)說明
gzip_comp_level 2;
# 進(jìn)行壓縮的文件類型,javascript有多種形,其中的值可以在 mime.types 文件中找到。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png font/ttf font/opentype image/svg+xml;
# 建議在http header中添加Vary: Accept-Encoding支持
gzip_vary on;
Nginx 之 靜態(tài)資源expires緩存過期時(shí)間配置
描述: 在 Nginx 配置 expires 指令可以起到控制頁面緩存的作用, 配置靜態(tài)資源的 expires 可以有效的減少客戶端對服務(wù)器的請求,該配置項(xiàng)適用于: http、server 以及 location 塊中。
expires(過期時(shí)間語法)語法示例
; 語法: `expires [time|epoch|max|off]`
* epoch:指定Expires的值為 1 January,1970,00:00:01 GMT
* max: 指定Expires的值為31 December2037 23:59:59GMT,"Cache-Control"的值為10年。
* -1:指定Expires的值為當(dāng)前服務(wù)器時(shí)間-1s,即永遠(yuǎn)過期。
* off:不修改Expires和"Cache-Control"的值
# location 塊 ~ 使用正則匹配
location ~ \.(gif|jpg|jpeg|png|bmp|ico)$ {
# 靜態(tài)資源源路徑必須配置否則,靜態(tài)資源可能無法找到
root /var/www/img/;
# 禁用404錯(cuò)誤日志
log_not_found off;
# 關(guān)閉access訪問日志
access_log off;
# 靜態(tài)資源過期時(shí)間
expires 7d;
}
該指令控制HTTP應(yīng)答中的"Expires"和"Cache-Control"Header頭部信息, 例如在配置后expires指令請求 https://blog.weiyigeek.top/img/avatar.jpg URL:
HTTP/1.1 304 Not Modified
Server: nginx
Date: Fri, 01 Apr 2022 09:19:09 GMT
Last-Modified: Wed, 30 Mar 2022 15:42:30 GMT
Connection: keep-alive
ETag: "62447a66-35db"
Expires: Fri, 08 Apr 2022 09:19:09 GMT # 表示資源過期時(shí)間,由當(dāng)前訪問時(shí)間加上max-age指令值所得
Cache-Control: max-age=604800 # 使用max-age指令指定組件被緩存多久,負(fù)數(shù)表示no-cache,正數(shù)或零表示max-age=time
Access-Control-Allow-Origin: *.weiyigeek.top
Access-Control-Allow-Methods: GET,POST
Access-Control-Allow-Headers: DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization
實(shí)踐示例:
# 網(wǎng)頁資源緩存
location ~* \.(xml|html|htm)$ {
# 資源決絕對目錄設(shè)置
root /var/www/html;
# 日志文件的相對路徑或完整路徑
access_log /path/to/file.log;
# 開啟日志記錄
access_log on;
# 設(shè)置過期時(shí)間
expires 24h;
}
# 樣式、JS、圖片資源緩存
location ~* \.(css|js|ico|gif|jpg|jpeg|png)$ {
root /var/www/html/res;
# 禁用404錯(cuò)誤日志
log_not_found off;
# 關(guān)閉日志
access_log off;
# 緩存時(shí)間7天
expires 7d;
}
# 字體資源緩存
location ~* \.(eot|ttf|otf|woff|woff2|svg)$ {
root /var/www/html/static;
log_not_found off;
access_log off;
expires max;
}
Nginx 之 反向代理資源基本緩存配置
描述: 在 Nginx 中往往我們會對指定站點(diǎn)進(jìn)行反代(反向代理), 而在反代站點(diǎn)中存在動態(tài)資源與靜態(tài)資源,我們可以使用下述指令開啟簡單的緩存配置。
首先我們需要了解一下三種緩存類型:
- 客戶端緩存
- 代理緩存(Proxy Cache)
- 服務(wù)端緩存
這里主要講解Nginx作為代理服務(wù)器進(jìn)行代理緩存的配置采用的參數(shù)以及示例:
- 1.
proxy_cache:定義用于緩存的共享內(nèi)存區(qū)域。同一個(gè)區(qū)域可以用于多個(gè)地方
Syntax: proxy_cache zone | off;
Default: proxy_cache off;
Context: http, server, location
- 2.
proxy_cache_path:設(shè)置緩存的路徑和其他參數(shù)緩存數(shù)據(jù)存儲在文件中,緩存中的文件名是將MD5函數(shù)應(yīng)用于緩存鍵的結(jié)果
Context: http
Syntax: proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
#例如,在下面的配置中l(wèi)evel參數(shù)定義緩存的層次結(jié)構(gòu)級別:從1到3,每個(gè)級別接受值1或2。
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m; #10M = 10 * 8000 個(gè)密鑰
#/data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029c
- 3.
proxy_cache_valid:設(shè)置緩存過期時(shí)間
Syntax: proxy_cache_valid [code ...] time;
Context: http, server, location
#例如,為不同的響應(yīng)代碼設(shè)置緩存時(shí)間。
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
#If only caching time is specified (指定),也可以可以指定any參數(shù)來緩存任何響應(yīng):
proxy_cache_valid 5m;
proxy_cache_valid any 1m;
- 4.
proxy_cache_key:設(shè)置緩存維度
Syntax: proxy_cache_key string;
Default: proxy_cache_key $scheme$proxy_host$request_uri;
Context: http, server, location
#例如,定義用于緩存的鍵,
proxy_cache_key "$host$request_uri $cookie_user";
proxy_cache_key $scheme$proxy_host$uri$is_args$args; #默認(rèn)情況下指令也是字符串不用加上""
- 5.
proxy_cache_purge:定義將在何種條件下將請求視為緩存清除請求。如果字符串參數(shù)中至少有一個(gè)值不為空且不等于“0”,則刪除具有相應(yīng)緩存鍵的緩存項(xiàng)。通過返回204 (No Content)響應(yīng)來指示操作成功的結(jié)果。
Syntax: proxy_cache_purge string ...;
Context: http, server, location
# Example configuration:
map $request_method $purge_method {
PURGE 1;
default 0;
}
- 6.
proxy_no_cache:指定不緩存的部分頁面,可以與proxy_cache_bypass指令一起使用。
Syntax: proxy_no_cache string ...;
Context: http, server, location
#如果字符串參數(shù)中至少有一個(gè)值不為空且不等于“0”,則不會保存響應(yīng):
proxy_no_cache $cookie_nocache $arg_nocache$arg_comment;
proxy_no_cache $http_pragma $http_authorization;
proxy_cache 相關(guān)指令集簡述
描述: 其中proxy_cache_path指令配置了緩存名稱以及其存放地址、緩存大小等相關(guān)其它參數(shù)配置, 而proxy_cache指令配置是為了啟用創(chuàng)建的mycache名稱的緩存。
- proxy_no_cache : 該指令用于定義滿足條件的響應(yīng)不會被保存到緩存中,在條件字符串中至少有一個(gè)條件不為空或者0,符合這樣條件的響應(yīng)才不會被緩存, 其一般會配合
proxy_cache_bypass共同使用; - proxy_cache_bypass : 該指令用于定義哪些情況不從cache讀取直接從backend獲取資源配置同上。
- proxy_cache_key : 該指令給緩存數(shù)據(jù)定義一個(gè)鍵。
- proxy_cache_methods :該指令用于設(shè)置緩存哪些HTTP方法,默認(rèn)緩存HTTP GET/HEAD方法不緩存POST方法。
- proxy_cache_valid :該指令用于設(shè)置不同響應(yīng)碼的緩存時(shí)間。
- proxy_cache_min_uses : 該指令用于設(shè)置緩存的最小使用次數(shù),默認(rèn)值為1
- proxy_cache_use_stale : 該指令開啟(增強(qiáng))容錯(cuò)能力,即使用緩存內(nèi)容來響應(yīng)客戶端的請求
示例演示:
# 1.其中,cookie_nocache、arg_nocache...皆為變量,可以根據(jù)你訪問的匹配策略來設(shè)置,其值只有2類,0和非0;
# 訪問匹配策略, 如果在此鏈?zhǔn)脚渲弥校灰幸粋€(gè)值不為 0 則不會cache。
if ($request_uri ~ ^/(login|register|password\/reset)/) { set $cookie_nocache 1; }
proxy_no_cache $cookie_nocache(0) $arg_nocache(1) $arg_comment(0)
proxy_no_cache $http_pragma $http_authorization;
# 2.默認(rèn)情況下,該指令的值的字符串,給緩存數(shù)據(jù)定義一個(gè)鍵。
proxy_cache_key $scheme$proxy_host$uri$is_args$args; # 缺省
proxy_cache_key $scheme$proxy_host$request_uri;
# 4.缺省緩存GET HEAD請求。
proxy_cache_methods GET HEAD;
# 5.只對響應(yīng)碼為200,301,302的訪問請求資源設(shè)置緩存時(shí)間,此外可以個(gè)性化定制。
proxy_cache_valid 200 302 10m;
proxy_cache_valid 301 1h;
proxy_cache_valid 404 1m;
proxy_cache_valid any 1m;
# 6.設(shè)置緩存的最小使用次數(shù)。
proxy_cache_min_uses 1;
# 7.當(dāng)作為cache的NGINX收到源站返回error、timeout或者其他指定的5XX錯(cuò)誤,并且在其緩存中有請求文件的陳舊版本,則會將這些陳舊版本的文件而不是錯(cuò)誤信息發(fā)送給客戶端。
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
實(shí)踐配置: 多磁盤分割緩存,如果有多個(gè)硬盤則可以用來在多個(gè)硬盤之間分割緩存。
# 假設(shè)每塊硬盤掛載在相應(yīng)的目錄中:/mnt/disk1、/mnt/disk2、/mnt/disk3, 使用了3個(gè)獨(dú)立的緩存,每個(gè)緩存專用一塊硬盤,另外,3個(gè)獨(dú)立的線程池也各自專用一塊硬盤。
proxy_cache_path /mnt/disk1 levels=1:2 keys_zone=cache_1:256m max_size=1024G use_temp_path=off;
proxy_cache_path /mnt/disk2 levels=1:2 keys_zone=cache_2:256m max_size=1024G use_temp_path=off;
proxy_cache_path /mnt/disk3 levels=1:2 keys_zone=cache_3:256m max_size=1024G use_temp_path=off;
# 緩存之間(其結(jié)果就是磁盤之間)的負(fù)載均衡使用 split_clients 模塊
split_clients $request_uri $disk {
33.3% 1;
33.3% 2;
* 3;
}
location / {
proxy_pass http://127.0.0.1:9090;
proxy_cache_key $request_uri;
proxy_cache cache_$disk;
}
實(shí)踐示例:
- 示例1.
proxy_cache_path /path/to/cache levels=1:2 keys_zone=mycache:10m max_size=10g inactive=60m use_temp_path=off;
upstream my_upstream {
server 192.168.1.20:8080 weight=5 max_fails=5 fail_timeout=30s;
server 192.168.1.10:8080 weight=5 max_fails=5 fail_timeout=30s;
}
server {
location / {
proxy_cache mycache;
proxy_pass http://my_upstream;
}
}
- 示例2:
http {
...
proxy_cache_path /opt/app levels:1:2 keys_zone=weiyigeek_cache:10m max_size=10g inactive=60m use_temp_path=off;
map $request_method $purge_method {
PURGE 1;
default 0;
}
...
server {
...
location / {
proxy_cache weiyigeek_cache;
proxy_pass http://weiyigeek;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_purge $purge_method;
add_header Nginx-Cache "$upstream_cache_status";
proxy_net_upstream error timeout invalid_header http_500 http_502;
include proxy_params;
}
...
}
}
溫馨提示: 在proxy_cache_path指令中的use_temp_path=off參數(shù),表示會將臨時(shí)文件保存在緩存數(shù)據(jù)的同一目錄中,此舉避免在更新緩存時(shí),磁盤之間互相復(fù)制響應(yīng)數(shù)據(jù),減少磁盤IO壓力。
補(bǔ)充說明:
問: 如何清理指定緩存?
> 1.rm -rf 刪除緩存目錄內(nèi)容
> 2.第三方擴(kuò)展模塊ngx_cache_purge
Nginx 之 黑白名單限制與請求限流
描述: 通常為了防止黑客攻擊以及惡意爬蟲爬取, 我們需要針對Nginx服務(wù)器配置黑白名單和限流措施。
黑白名單之deny 與 allow
描述: 利用 include 指令添加黑白名單配置文件,該指令可以在http, server, location, limit_except語句塊,例如:
# 白名單
include whiteip.conf;
# allow 192.168.12.0/24; # 允許IP段
# allow 127.0.0.1; # 允許單個(gè)IP
# allow all; # 允許所有IP
# 黑名單
include blockip.conf;
# deny 127.0.0.1; # 屏蔽單個(gè)IP
# deny all; # 屏蔽所有IP
溫馨提示: 當(dāng)被屏蔽的 IP 再次訪問我們的nginx服務(wù)器網(wǎng)頁是,將會顯示 403 頁面。
訪問限制之并發(fā)連接與請求速率
描述: 我們可以分別利用Nginx提供的 limit_conn_zone 與 limit_req_zone 模塊來限制每個(gè)IP的連接數(shù)以及請求數(shù)。$binary_remote_addr 是限制同一客戶端ip地址(節(jié)約空間), 注意不是使用$remote_addr變量;
http {
# - limit_conn_zone:限制每個(gè)IP的并發(fā)連接數(shù)
# 例如 blogweiyigeektop 是定義的一個(gè)會話區(qū)其用于記錄會話狀態(tài)信息。
limit_conn_zone $binary_remote_addr zone=blogweiyigeektop:10m;
limit_conn_zone $server_name zone=serverweiyigeektop:10m;
limit_conn_log_level info;
# - limit_req_zone:限制每個(gè)IP的請求數(shù)
limit_req_zone $binary_remote_addr zone=weiyigeek_top:10m rate=1r/s;
limit_req_zone $binary_remote_addr $uri zone=blog_weiyigeek_top:3m rate=1r/s; # $uri 表示同個(gè)ip 訪問同個(gè)uri 才會進(jìn)入限制
server {
# 限連接數(shù)
location ^~ /download1/ {
limit_conn serverweiyigeektop 1000; # 表示該服務(wù)提供的總連接數(shù)最大不超過1000,超過的請求會被拒絕
limit_conn blogweiyigeektop 4; # 表示對blogweiyigeektop空間中的每個(gè)IP的最大并發(fā)連接數(shù)為4
limit_rate 200k; # 注意此處是對連接的限速不是對IP的限速
alias /data/www.weiyigeek.top/download1/;
}
# 限請求速率
location ^~ /download2/ {
# 允許超過頻率限制的請求數(shù)不多于5個(gè),無延遲表示請求超過頻次時(shí),可提供處理(burst + rate)個(gè)請求的能力,注意 nodelay 是要和 burst 配合使用的。
limit_req zone=weiyigeek_top burst=5 nodelay;
alias /data/blog.weiyigeek.top/download2/;
}
}
}
動態(tài)屏蔽惡意IP
Step 1.從logs目錄下日志文件中安裝指定規(guī)則查找要屏蔽的IP執(zhí)行如下命令awk '{print $1}' access.log |sort |uniq -c|sort -n即可,就可以統(tǒng)計(jì)出IP的訪問次數(shù)。
68 218.76.35.4
73 42.192.96.35
94 139.155.14.45
221 223.202.212.140
- Step 2.自動化腳本簡單實(shí)現(xiàn)訪問請求次數(shù)多的IP將進(jìn)行封禁,
#! /bin/bash
log_nginx="/var/log/nginx" # nginx日志文件
blockfile="/usr/local/nginx/conf.d" # ip黑名單存放目錄
ip_tempfile="/tmp/nginx/ip.txt"
# 取出日志中符合條件的ip寫入ip.txt,并過濾掉重復(fù)的
grep "/atom.xml" $log_nginx/access.log | awk '{print $1}' | sort -rn |uniq -c |awk '{print $2}' > /tmp/nginx/ip.txt
for ip in `cat /home/shell/ip.txt`;do
result=$(grep $ip $blockfile/blockip.conf)
#判斷ip是否已經(jīng)被屏蔽
if [ -z "$result" ]; then
#分析ip請求的次數(shù)
count=$(grep $ip $log_nginx/access.log|grep "app/user/getCode"|wc -l)
# 請求次數(shù)大于等于20次就進(jìn)行屏蔽
if [ $count -ge 20 ]; then
echo "deny $ip;" >> $blockfile/blockip.conf
fi
fi
done
#重啟nginx
/usr/local/nginx/sbin/nginx -s reload
溫馨提示: 上述并不是一個(gè)非常好的方式,此種方式誤殺明顯,建議與請求限制聯(lián)合使用,于此同時(shí)我們可以利用Lua + redis實(shí)現(xiàn)一個(gè)動態(tài)封禁與解封(這個(gè)后續(xù)在實(shí)現(xiàn))。
白名單與限制聯(lián)合使用:
描述: 如果 Nginx 前面有 lvs 或者 haproxy 之類的負(fù)載均衡或者反向代理,nginx 獲取的都是來自負(fù)載均衡的連接或請求,此時(shí)是不應(yīng)該限制負(fù)載均衡的連接和請求,這就需要 geo 和 map 模塊設(shè)置白名單了;
geo $whiteiplist {
default 1;
10.11.15.161 0;
}
map $whiteiplist $limit {
1 $binary_remote_addr;
0 "";
}
limit_req_zone $limit zone=one:10m rate=10r/s;
limit_conn_zone $limit zone=addr:10m;
原文連接: https://blog.weiyigeek.top/2019/9-1-124.html
文章書寫不易,如果您覺得這篇文章還不錯(cuò)的,請給這篇專欄 【點(diǎn)個(gè)贊、投個(gè)幣、收個(gè)藏、關(guān)個(gè)注,轉(zhuǎn)個(gè)發(fā)】(人間五大情),這將對我的肯定,謝謝!。
本文章來源 我的Blog站點(diǎn) 或 WeiyiGeek 公眾賬號 以及 我的BiliBili專欄 (
技術(shù)交流、友鏈交換請郵我喲),謝謝支持!(?′?‵?) ?
歡迎各位志同道合的朋友一起學(xué)習(xí)交流,如文章有誤請留下您寶貴的知識建議,通過郵箱【master#weiyigeek.top】聯(lián)系我喲!
本文來自博客園,作者:全棧工程師修煉指南,轉(zhuǎn)載請注明原文鏈接:http://www.rzrgm.cn/WeiyiGeek/p/16148564.html。
歡迎關(guān)注博主【W(wǎng)eiyiGeek】公眾號以及【極客全棧修煉】小程序

浙公網(wǎng)安備 33010602011771號