Nginx
概述
NGINX is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. NGINX is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.
NGINX is one of a handful of servers written to address the C10K problem. Unlike traditional servers, NGINX doesn’t rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load. Even if you don’t expect to handle thousands of simultaneous requests, you can still benefit from NGINX’s high-performance and small memory footprint. NGINX scales in all directions: from the smallest VPS all the way up to large clusters of servers.
NGINX powers several high-visibility sites, such as Netflix, Hulu, Pinterest, CloudFlare, Airbnb, WordPress.com, GitHub, SoundCloud, Zynga, Eventbrite, Zappos, Media Temple, Heroku, RightScale, Engine Yard, MaxCDN and many others.
Nginx可以是:
-
httpd協議的web服務器,其對于靜態資源有無與倫比的響應能力
-
反向代理服務:代理FastCGI/uwSCGI/SCGI、httpd、imap4/pop3協議、tpc/udp協議
-
緩存服務器:緩存動態資源
Nginx程序采用高度模塊化設計,但早期不支持DSO機制,如今已支持模塊動態裝載和卸載;
-
核心模塊:core module
-
標準模塊:Standard HTTP modules、Optional HTTP modules、Mail modules、Stream modules、3rd party modules
Nginx處理事務的架構為mater/worker
-
master:負責加載配置文件,管理worker進程;
-
worker:處理N個用戶的請求;
-
緩存相關進程:cache loader、cache manager;
Nginx支持異步IO機制,協調master與worker之間的工作效率
-
事件驅動、異步IO、非阻塞是Nginx最重要特性,這種由被調用者通過狀態、通知或回調機制通知調用者被調用者的運行狀態的機制使得Nginx能夠處理大量的并發請求。
-
阻塞型IO需等待數據加載過程的兩階段,處于掛起狀態;非阻塞型IO無需等待第一階段的磁盤加載過程,但仍需周期性檢查數據是否已經準備好,屬于第一階段為忙等待,第二階段仍為阻塞類型的IO,即進程在此期間無法處理任何請求。
-
復用型IO使得進程不阻塞于第一階段的系統IO上,而是阻塞在內核空間提供的復用IO上。同步IO雖無需等待第一階段的IO,但第二階段仍需阻塞加載數據,其回調機制使得進程在第一階段是空閑的,因此一個進程可以處理多個請求;異步IO則使進程兩個階段都不阻塞,其事件驅動與異步IO架構,使得一個進程可處理更多的請求。
-
yum安裝Nginx
-
準備yum源或rpm包
#官方提供的yum倉庫
vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/
gpgcheck=0
enabled=1
yum -y install nginx
#或下載最新的rpm包進行安裝
yum -y install ./nginx.xx.rpm
-
啟動前的配置
cp /etc/nginx.conf{,.bak}
vi /etc/nginx.conf
cp /etc/nginx/conf.d/default.conf{,.bak}
vi /usr/share/nginx/html/admin/index.html
-
啟動nginx
nginx
ss -tnl | grep ":80\>"
編譯安裝Nginx
[官方wiki]http://nginx.org/en/docs/configure.html
-
準備開發環境、依賴程序包
yum install pcre-devel openssl-devel zlib-devel
-
創建
nginx
用戶
useradd -r nginx
-
獲取源碼包,編譯安裝
tar xf nginx-1.10.0.tar.gz
./configure --help #獲取編譯幫助,有N多模塊可選
./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_dav_module --with-http_stub_status_module --with-threads --with-file-aio
#編譯結果
Configuration summary
+ using threads
+ using system PCRE library
+ using system OpenSSL library
+ md5: using OpenSSL library
+ sha1: using OpenSSL library
+ using system zlib library
nginx path prefix: "/usr/local/nginx"
nginx binary file: "/usr/local/nginx/sbin/nginx"
nginx modules path: "/usr/local/nginx/modules"
nginx configuration prefix: "/etc/nginx"
nginx configuration file: "/etc/nginx/nginx.conf"
nginx pid file: "/var/run/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: "client_body_temp"
nginx http proxy temporary files: "proxy_temp"
nginx http fastcgi temporary files: "fastcgi_temp"
nginx http uwsgi temporary files: "uwsgi_temp"
nginx http scgi temporary files: "scgi_temp"
#開始編譯
make -j2 && make install
#添加環境變量
echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
-
命令使用
nginx -h
(1)nginx
(2)nginx -s signal: send signal to a master process: stop, quit, reopen, reload
主要文件路徑
配置文件: /etc/nginx/nginx.conf
, /etc/nginx/conf.d/*.conf
fastcgi uwsgi scgi等相關配置文件:fastcgi_params
mime.types:支持的mimie類型:mime.types
程序文件:
Excusetable:/usr/sbin/nginx
, /usr/sbin/nginx-debug
Unit File:/usr/lib/systemd/system/nginx.service
,/usr/lib/systemd/system/nginx-debug.service
Modules:/usr/lib64/nginx/modules
站點:/usr/share/nginx, /usr/share/nginx/html, /usr/share/nginx/html/50x.html, /usr/share/nginx/html/index.html
日志:/var/log/nginx
緩存:/var/cache/nginx
主配置文件nginx.conf
配置文件有眾多的指令組成,格式為:
-
directive value [value2 …];注意:指令必須以分號結尾
配置文件中的變量:
-
內建變量:有Nginx模塊引入,可直接引用
-
自定義變量:set $variable value;
main block:全局配置段
main block:全局配置段
…… #正常運行必備的配置、優化性能等
#事件驅動相關的配置
event{
}
mail{
}
stream{
}
http/https 協議相關配置段
http{
……
server的公共配置
server{
……
}:一個server一個虛擬主機
server{
server_name
root
location [OPERATOR] URL{
alias
……
if CONDITION{
……
}
}
}
}
性能優化初步
-
【1】worker_cpu_affinity cpumask …;
worker_cpu_affinity auto [cpumask];
cpumask:0101 1010;每worker進程使用一個十六進制位親和最多4核心的CPU -
【2】worker_priority number
from -20 to 20, a negative number means higher priority -
【3】worker_rlimit_nofile number
the limit on the maximum number of open files (RLIMIT_NOFILE) for worker processes
調試、定位問題的配置
-
daemon on|off; 是否以守護進程運行在后臺
-
master_process on | off; 是否以master/worker運行nginx,否則只運行master
-
error_log file [level]; 在各段或只在main中同一記錄日志
events段配置
worker、method、accept_mutex
events{
worker_connections number; #每worker最大并發連接數,worker_process * worker_connect為總并發
use method; #use epol,
accept_mutex on|off #處理新連接請求的方法,on為turn,off為通知所有worker,在httpd上會造成驚群問題造成上下文切換過載。關閉時用ngx-req-distr工具測試發現每個worker處理的請求數較平均。
}
http協議相關配置段
虛擬主機
-
【1】server;定義虛擬主機,一般單獨寫在conf.d目錄下
server{
listen ip[:port] | port
server_name
root
location [OPERATOR] /url/{
……
}
}
-
【2】listen address[:port] [default_server] [ssl] [http2 | spdy] [backlog=number] [sndbuf=size] [accept_filter=filter];
-
【3】server_name name …;空白字符分隔開的多個name
-
*.example.com www.example.*
:以 * 通配任意字符 -
~^www\d+\.example\.com$
:以 ~ 匹配的正則表達式模式 -
優先級:精確 > *. 通配符 > 通配符 .* > 正則
基于PORT、IP、Server Name的虛擬主機示例
單個IP可定義多個不同PORT虛擬主機,單個IP的單個PORT可定義多個不同Server Name的虛擬主機。因此,常用的虛擬主機為基于PORT與Server Name的虛擬主機。
vi /etc/nginx/conf.d/vhost.conf
server {
listen 8080;
server_name localhost;
root /data/nginx/port;
}
server {
listen 10.1.253.69;
server_name localhost;
root /data/nginx/ip1;
}
server {
listen 10.1.253.70;
server_name www2.jasonmc.com;
root /data/nginx/ip2;
}
server {
listen 10.1.253.69;
server_name www1.jasonmc.com;
root /data/nginx/www1;
}
server {
listen 10.1.253.69;
server_name www2.jasonmc.com;
root /data/nginx/www2;
}
與套接字相關的配置(sendfile、nodelay)
-
【4】tcp_nodelay on | off;在keepalived模式下,當用戶請求的資源較少時,默認把多個資源打包發送,雖省資源,但影響用戶體驗
-
【5】sendfile on | off;內核級別直接封裝用戶請求的資源,不復制到進程內存再封裝以提高響應速度
定義路徑相關配置
-
【6】root path;設置web資源路徑映射,指明url所對應在本地文件系統的路徑,可在 http, server, locationduan定義,在
//host/path --> Newpath/path/index.html
-
【7】location @name { … }
在一個server中可有多個location,用于映射url到其他路徑,nginx會根據請求的URI匹配一個最佳的路徑 -
location [ = | ~ | ~* | ^~ ] uri { … }
=:對URI精確匹配,如www.exp.com/與www.exp.com/index.html將映射在不同的location中
~:對URI正則表達式匹配,區分字符大小寫
~*:對URI正則表達式匹配,不區分大小寫
^~:對URI左半部分正則匹配,不區分大小寫
/:不帶符號將匹配沒人要的URI
優先級:匹配范圍小的優先級高 =, ^~, ~*/~, /
定義 URL 對應的 root 示例
vi /etc/nginx/conf.d/default.conf
locaction /admin/ {
root /data/nginx/;映射為/data/nginx/admin/index.html
#或alias把//host/admin/index.html映射到/data/nginx/index.html
}
-
【8】alias path;定義在location中,與root的區別在于path直接映射為url的根,無需在路徑中建立對應的目錄。如//host/path –> Newpath/index.html
-
【9】index file…;定義首頁文件,可在http、server、locaton中定義,虛擬主機一般在server中定義。
-
【10】error_page code … [=[response]] uri;錯誤碼和錯誤頁
Defines the URI that will be shown for the specified errors.
定義錯誤頁示例
vi /etc/nginx/conf.d/default.conf
error_page 404 /404.html;如果404 =200則響應碼為200,ok
location = /404.html{
root /usr/share/nginx/html/error_page/;
}
-
【11】try_files file … uri;
try_files file … =code;
客戶端請求相關配置
-
【12】keepalive_requests number;在一次長連接所允許的最大請求次數,默認100
-
【13】keepalive_timeout timeout [header_timeout];保持連接超時時長,0表示禁止長連接,默認75s
-
【14】keepalive_disable none | browser …;對哪種瀏覽器禁用長連接
-
【15】send_timeout time;向客戶端發送響應報文的超時時長
-
【16】client_body_buffer_size size;緩沖請求報文的body部分,默認16k,超出則存在文件中
-
【17】client_body_temp_path path [level1 [level2 [level3]]];超出內存緩沖16k,存儲在磁盤路徑中,索引方式采用目錄分層結構,一般3層結構即可
-
client_body_temp_path /var/tmp/client_body 1 2 2;
每層最多2個16進制位
限定客戶端速率與請求方法
-
【18】limit_rate rate;默認0為不限制,單位bytes
-
【19】limit_except method … { … };限制常用請求方法以外的請求方法允許誰使用
除GET方法以外允許誰訪問的示例
server{
limit_except GET {
allow 192.168.1.0/32;
deny all;
}
}
文件操作優化配置(ngx_http_core_module)
-
【20】aio on | off | threads[=pool];異步IO,nginx的最大特性,提升性能
-
【21】directio size | off;在Linux中,接收或加載的文件大小超過給定的size時,直接存取磁盤,不經過內存
-
【22】open_file_cache max=N [inactive=time];超過max閥值或inactive之后,LRU算法進行清理非活動項,能夠緩存文件描述符、大小、修改時間、目錄結構、存在及權限信息
-
open_file_cache off;
-
【23】open_file_cache_min_uses number;在inactive指定的時間活內動項被命中的次數
-
【24】open_file_cache_valid time;緩存有效期的檢查頻率,活動還是非活動,默認60s
-
【25】open_file_cache_errors on | off;
基于ip的訪問控制功能(ngx_http_access_module)
-
【26】allow address | CIDR | unix: | all;
-
【27】deny address | CIDR | unix: | all;
基于用戶的訪問控制功能(ngx_http_auth_basic_module)
-
【28】auth_basic string | off;
-
【29】auth_basic_user_file file;
用戶驗證示例
location / {
……
auth_basic "we need to authority.";
auth_basic_user_file /etc/nginx/.ngxpasswd;
}
#生成驗證所需的賬號和密碼,使用htpasswd工具
yum install httpd-tools
htpasswd -c -m /etc/nginx/.ngxpasswd tom
htpasswd -m /etc/nginx/.ngxpasswd alice
stub狀態信息頁(ngx_http_stub_status_module)
-
【30】stub_status;在某一location中定義請求時自動生成相關信息
stub_status配置示例
location /basic_status {
stub_status;
access_log off; #location中暫定為無法阻斷日志輸出
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#輸出的實時數據:
Active connections: 291 #當前連接數
server accepts handled requests #匯總的數據
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106 #讀取客戶端報文、向客戶端發送、等待客戶端發送的幾種連接數
日志管理模塊(ngx_http_log_module)
The ngx_http_log_module module writes request logs in the specified format.
常用內置變量
$remote_addr, \$http_x_forwarded_for 記錄客戶端IP地址
$remote_user 記錄客戶端用戶名稱
$request 記錄請求的URL和HTTP協議
$status 記錄請求狀態
$body_bytes_sent 發送給客戶端的字節數,不包括響應頭的大小; 該變量與Apache模塊mod_log_config里的“%B”參數兼容
$bytes_sent 發送給客戶端的總字節數
$connection 連接的序列號
$connection_requests 當前通過一個連接獲得的請求數量
$msec 日志寫入時間。單位為秒,精度是毫秒
$pipe 如果請求是通過HTTP流水線(pipelined)發送,pipe值為“p”,否則為“.”
$http_referer 記錄從哪個頁面鏈接訪問過來的
$http_user_agent 記錄客戶端瀏覽器相關信息
$request_length 請求的長度(包括請求行,請求頭和請求正文)
$request_time 請求處理時間,單位為秒,精度毫秒; 從讀入客戶端的第一個字節開始,直到把最后一個字符發送給客戶端后進行日志寫入為止
$time_iso8601 ISO8601標準格式下的本地時間
$time_local 通用日志格式下的本地時間
-
【31】log_format name string …;
日志格式,使用nginx內建變量ngx_http_core_module中被編譯到core中的模塊所提供的變量,Embedded Variables中有相關的描述 -
【32】access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
-
buffer=size:日志在內存緩存空間大小
-
flush=time:指定緩存到磁盤的時間
-
access_log off;
-
access_log /path/to/log.gz combined gzip flush=5m;
-
【33】open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
緩存打開的日志文件描述符信息,加速日志文件元數據的操作 -
open_log_file_cache off;
-
max:最大緩存文件描述符數量
-
inactive:非活動時長,默認10s
-
min_users:在inactive時間內,活動項應有的訪問次數
-
valid:驗證緩存項是否為活動狀態,根據inactive和min_users識別,默認60s
-
open_log_file_cache max=1001 inactive=16s valid=60s min_users=2;
log_format默認格式
vi /etc/nginx/nginx.conf
log_format compression '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" "$gzip_ratio"';
log_format適用于反向代理
#nginx作為反向代理服務器,記錄客戶端真實ip及轉發的日志信息
log_format main
'$remote_addr - $remote_user [$time_local] "$request" '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'"$gzip_ratio" $request_time $bytes_sent $request_length';
log_format適用于SRCache緩存
#分布式緩存SRCache相關的日志
log_format srcache_log
'$remote_addr - $remote_user [$time_local] "$request" '
'"$status" $body_bytes_sent $request_time $bytes_sent $request_length '
'[$upstream_response_time] [$srcache_fetch_status] [$srcache_store_status] [$srcache_expire]';
log_format適用于json格式
#記錄json格式的日志,便于logstash分析日志
log_format logstash_json '{ "@timestamp": "$time_local", '
'"@fields": { '
'"remote_addr": "$remote_addr", '
'"remote_user": "$remote_user", '
'"body_bytes_sent": "$body_bytes_sent", '
'"request_time": "$request_time", '
'"status": "$status", '
'"request": "$request", '
'"request_method": "$request_method", '
'"http_referrer": "$http_referer", '
'"body_bytes_sent":"$body_bytes_sent", '
'"http_x_forwarded_for": "$http_x_forwarded_for", '
'"http_user_agent": "$http_user_agent" } }';
##經過http://jsonlint.com/轉換之后非常便于閱讀與分析
{
"@timestamp": "25/Oct/2016:15:15:38 +0800",
"@fields": {
"remote_addr": "192.168.1.26",
"remote_user": "-",
"body_bytes_sent": "9",
"request_time": "0.000",
"status": "200",
"request": "GET / HTTP/1.1",
"request_method": "GET",
"http_referrer": "http://www.pma.com",
"body_bytes_sent": "9",
"http_x_forwarded_for": "-",
"http_user_agent": "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.21 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2"
}
}
URL重寫(ngx_http_rewrite_module)
能夠實現將用戶請求的URI基于regex進行匹配,并replacement為新的URI
注意:在同一級配置塊中的多個rewrite規則將按順序逐一匹配,每替換一次就產生新的URI,如果后續的rewrite能夠繼續匹配新的URI,直到最終的替換結果,可能出現無限循環。因此,[flag]標記可避免這種情況。
status:
301:永久重定向,對該URI顯示為Moved Permanently,可被緩存(from cache)
302:臨時從定向,對該URI顯示為Moved Temporarily,一般不被Browser緩存
-
【rewrite flag】:默認為last,由服務端nginx系統不斷循環重新匹配,直到無法再匹配到
-
last
:在一個location中匹配到URI就停止當前循環,把新的URI在location從頭開始匹配 -
break
:在一個location中匹配到URI就停止當前循環 -
redirect
:重寫URI后以臨時重定向發送給客戶端,客戶端請求新的URL,code為302 -
permanent
:重寫URI后以永久從定向方式發送給客戶端,客戶端請求新的URL,code為301 -
【1】rewrite regex replacement [flag];
-
【2】rewrite_log on | off;記錄重寫日志
location中URL重寫示例
vi /etc/nginx/conf.d/default.conf
location / {
root /usr/share/nginx/html;
index index.php index.html index.htm;
rewrite ^/fz(.*) https://www.google.com redirect;
#rewrite ^/(.*)$ https://www.pma.com/$1; #全站https
}
-
【3】return code [text];return code URL;return URL;
Stops processing and returns the specified code to a client. -
【4】if (condition) { … }
引入一個新的配置段,條件滿足時執行段內指令,運用在server、location中condition
: -
比較操作符
= =
!=
~:模式匹配,區分字符大小寫;
~*:模式匹配,不區分字符大小寫;
!~:模式不匹配,區分字符大小寫;
!~*:模式不匹配,不區分字符大小寫; -
文件及目錄存在性判斷
-e, !-e
-f, !-f
-d, !-d
-x, !-x -
【5】set $variable value;
自定義變量,系統變量可在ngx_http_core_module的Embedded Variables中查看
location中if條件示例
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}
if ($slow) {
limit_rate 10k;
}
if ($invalid_referer) {
return 403;
}
if ($request_method = POST) {
return 405;
}
gzip壓縮功能ngx_http_gzip_module
The ngx_http_gzip_module module is a filter that compresses responses using the “gzip” method.
-
【1】gzip on | off;
-
【2】gzip_comp_level level;
Sets a gzip compression level of a response. the range from 1 to 9. -
【3】gzip_disable regex …;
Disables gzipping of responses for requests with “User-Agent” header fields matching any of the specified regular expressions. -
【4】gzip_min_length length;
Sets the minimum length of a response that will be gzipped. -
【5】gzip_buffers number size;
Sets the number and size of buffers used to compress a response. -
【6】gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any …;由nginx作為代理服務器,轉發響應報文時在何種情況下啟用壓縮功能。
-
no-cache, no-store, private
:大致表示對不緩存的內容啟用壓縮,報文中有三者中任一值都啟用壓縮。 -
【7】gzip_vary on | off;
GZip壓縮示例
http{
gzip on;
gzip_comp_level 5;
#gzip_disable .*MSIE.*;
gzip_type text/plain, text/css, text/xml;
gzip_min_length 1K;
gzip_vary on; #增加報文Vary:Accept-Encoding
gzip_disable Chrome;
}
#拷貝文件做測試
cp /var/log/messages /usr/share/nginx/html/messages.html
chmod +x
#測試
curl -I http://ip/file
Vary:Accept-Enconding #響應報文告訴客戶端支持壓縮
curl --compressed -I http://ip/file
Vary:gzip #使用gzip壓縮,明顯減小Content-Length
fastcgi反向代理(ngx_http_fastcgi_module)
The ngx_http_fastcgi_module module allows passing requests to a FastCGI server.
nginx作為反向代理服務器,實現lnmp的web框架
-
【1】fastcgi_pass address;映射fastcgi server在location
-
【2】fastcgi_index name;
-
【3】fastcgi_param parameter value [if_not_empty];傳遞給后端服務器的變量值,在fastcgi_params文件中定義
fastcgi_param QUERY_STRING /path/$query_string;
把nginx的query_string傳遞給fpm的QUERY_STRING變量
FastCGI代理至fpm示例
vi /etc/nginx/conf.c/default.conf
server {
index index.php index.html index.htm
location ~ \.php$ {
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/$fastcgi_script_name; 或/$fastcgi_script_name
include fastcgi_params;
}
location ~* ^/(fpm-status|ping)$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
include fastcgi_params;
}
}
-
【4】fastcgi_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];
定義fastcgi的緩存,緩存位置為磁盤上的文件系統路徑,由path指定 -
levels=level1:level2:緩存目錄的層級結構,16進制位數,每層最多2位
緩存的存放方式:對URL做hash運算,md5值的倒數幾位作為存放目錄層級結構的路徑,hash表使用keys_zone定義,記錄了key/value的映射關系 -
keys_zone=name:size:key/value使用的內存區域名及大學
-
inactive=time:非活動時長
-
max_size=size:磁盤上用于緩存fastcgi數據的上限,放在SSD中可加速
-
【5】fastcgi_cache zone | off;開啟代理緩存,使用keys_zone定義的區域
-
【6】fastcgi_cache_key string;定義用作緩存項的key字符串
-
【7】fastcgi_cache_methods GET | HEAD | POST …;為哪些請求方法啟用緩存
-
【8】fastcgi_cache_min_uses number;活動項的最少命中次數
-
【9】fastcgi_cache_valid [code …] time;不同響應碼的緩存時長,如404被緩存5分鐘
-
【10】fastcgi_keep_conn on | off;向后端fpm服務器開啟保存連接,應對大量并發訪問
開啟FastCGI緩存示例
vi /etc/nginx/nginx.conf
http{
fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2:2 keys_zone=fcgi:20m inactive=120s;
}
vi /etc/nginx/conf.d/default.conf
location ~ \.php$ {
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/$fastcgi_script_name;
include fastcgi_params;
fastcgi_cache fcgi; #在http{}中定義的key_zone=fcgi
fastcgi_cache_key $request_uri;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 301 1h;
fastcgi_cache_valid any 1m;
}
#緩存目錄在/var/cache/nginx/fastcgi_cache中,自動生成該目錄
ssl模塊(ngx_http_ssl_module)
-
【1】ssl on | off;允許HTTPS protocol for the given virtual server.
-
【2】ssl_certificate file;
-
【3】ssl_certificate_key file;
-
【4】ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
支持的ssl版本,建議使用1.1,默認為后三個 -
【5】ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
-
builtin[:size]使用openssl內建的緩存,此緩存為每個worker進程私有
-
shared:name:size在多個worker進程間使用共享內存,便于切換
-
【6】ssl_session_timeout time;緩存的有效時長
開啟https的phpMyAdmin示例
【配置虛擬主機https協議的PhpMyAdmin】
vi /etc/nginx/conf.d/pma_ssl.conf
server {
listen 443 ssl;
server_name www.pma.com;
location / {
root /usr/share/nginx/vhost/htdoc/pma;
index index.php
}
location ~* \.php$ {
root /usr/share/nginx/vhost/htdoc/pma;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/vhost/htdoc/pma/$fastcgi_script_name;
include fastcgi_params;
fastcgi_cache fcgi;
fastcgi_cache_key $request_uri;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 301 1h;
fastcgi_cache_valid any 1m;
}
ssl on;
ssl_certificate /etc/httpd/certs/www_pma_com.crt
ssl_certificate_key /etc/httpd/certs/httpd.key
ssl_session_cache shared:sslcache:10m;
access_log /var/log/nginx/access_json.log logstash_json;
valid_referers none block server_names *.pma.com pma.* ~\.pma\.;
if ($invalid_referer) {
return 403;
}
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#全站https,把80端口跳轉到固定鏈接
vi /etc/nginx/conf.d/default.conf
rewrite ^/(.*)$ https://www.pma.com/$1
資源防盜鏈模塊(ngx_http_referer_module)
-
【1】valid_referers none | blocked | server_names | string …;定義referer首部的合法可用值;
-
none:請求首部沒有referer首部
-
block:請求報文的referer首部沒有值
-
server_names:參數,其值作為主機名或主機名的模式
arbitrary_string:直接字符串,可用*匹配
regular_expression:被指定正則式匹配到的字符串,~.*.jasonmc.com
配置示例
server {
……
location{
……
}
valid_referers none block server_name *.jasonmc.com jasonmc.* ~\.jasonmc\.;
if ($invalid_referer) {
return 403;
}
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#客戶端測試,偽裝referer來源
curl -k -e "http://www.jasonmc.com" https://10.1.253.29/index.html
curl -k -e "http://www.baidu.com" https://10.1.253.29/index.html
總結
Nginx擁有豐富的擴展,其官網提供了非常全面的介紹。雖說是沒有中文,但對于各位英語達人而言……
【real1】http禁止ip訪問(重定向),https禁止ip訪問(錯誤頁),全站https
#http禁止ip訪問
server {
listen 80;
server_name localhost;
#返回404
error_page 404 /404.html;
location = /404.html {
#重寫URL
rewrite /404.html http://www.178linux.com/author/jasonmc permanent;
#或自定義錯誤頁
#root /data/blog/error_page/;
}
#直接返回301重定向
#return 302 http://www.google.com;
}
#https禁止ip訪問
server {
listen 443 ssl default_server;
server_name localhost;
ssl_certificate /etc/nginx/certs/jasonmc_com.crt;
ssl_certificate_key /etc/nginx/certs/jasonmc.key;
error_page 404 /404.html;
location = /404.html {
#rewrite /404.html http://www.www58058.com/author/jasonmc permanent;
root /data/blog/error_page/;
}
#return 301 http://www.google.com;
}
#基于主機名的虛擬主機,重定向80端口
server {
listen 80;
server_name www.jasonmc.com;
rewrite ^/(.*)$ https://www.jasonmc.me/$1 permanent;
}
#基于主機名的https虛擬主機
server {
listen 443 ssl;
server_name www.jasonmc.com jasonmc.com;
location / {
root /data/blog;
index index.html index.htm;
}
ssl on;
ssl_certificate /etc/nginx/certs/jasonmc_com.crt;
ssl_certificate_key /etc/nginx/certs/jasonmc.key;
ssl_session_cache shared:sslcache:10m;
valid_referers none block server_names *.jasonmc.com jasonmc.* ~\.jasonmc\.;
if ($invalid_referer) {
return 403;
}
}
原創文章,作者:helloc,如若轉載,請注明出處:http://www.www58058.com/54499