一、安裝Nginx:
1、解決依賴關(guān)系
# yum groupinstall "Development Tools" "Server Platform Deveopment"
# yum install openssl-devel pcre-devel
2、安裝
首先添加用戶nginx,實(shí)現(xiàn)以之運(yùn)行nginx服務(wù)進(jìn)程:
# groupadd -r nginx
# useradd -r -g nginx nginx
接著開(kāi)始編譯和安裝:
# ./configure \
--prefix=/usr \
--sbin-path=/usr/sbin/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/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_flv_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/tmp/nginx/client/ \
--http-proxy-temp-path=/var/tmp/nginx/proxy/ \
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
--http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
--http-scgi-temp-path=/var/tmp/nginx/scgi \
--with-pcre
# make && make install
說(shuō)明:
1、Nginx可以使用Tmalloc(快速、多線程的malloc庫(kù)及優(yōu)秀性能分析工具)來(lái)加速內(nèi)存分配,使用此功能需要事先安裝gperftools,而后在編譯nginx添加--with-google_perftools_module選項(xiàng)即可。
2、如果想使用nginx的perl模塊,可以通過(guò)為configure腳本添加--with-http_perl_module選項(xiàng)來(lái)實(shí)現(xiàn),但目前此模塊仍處于實(shí)驗(yàn)性使用階段,可能會(huì)在運(yùn)行中出現(xiàn)意外,因此,其實(shí)現(xiàn)方式這里不再介紹。如果想使用基于nginx的cgi功能,也可以基于FCGI來(lái)實(shí)現(xiàn),具體實(shí)現(xiàn)方法請(qǐng)參照網(wǎng)上的文檔。
3、為nginx提供SysV init腳本:
新建文件/etc/rc.d/init.d/nginx,內(nèi)容如下:
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/nginx.conf
# config: /etc/sysconfig/nginx
# pidfile: /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/ngin
lockfile=/var/lock/subsys/nginx
make_dirs() {
# make required directories
user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
options=`$nginx -V 2>&1 | grep 'configure arguments:'`
for opt in $options; do
if [ `echo $opt | grep '.*-temp-path'` ]; then
value=`echo $opt | cut -d "=" -f 2`
if [ ! -d "$value" ]; then
# echo "creating" $value
mkdir -p $value && chown -R $user $value
fi
fi
done
}
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
make_dirs
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
sleep 1
start
}
reload() {
configtest || return $?
echo -n $"Reloading $prog: "
killproc $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
exit 2
esac
而后為此腳本賦予執(zhí)行權(quán)限:
# chmod +x /etc/rc.d/init.d/nginx
添加至服務(wù)管理列表,并讓其開(kāi)機(jī)自動(dòng)啟動(dòng):
# chkconfig --add nginx
# chkconfig nginx on
而后就可以啟動(dòng)服務(wù)并測(cè)試了:
# service nginx start
二、配置Nginx
Nginx的代碼是由一個(gè)核心和一系列的模塊組成, 核心主要用于提供Web Server的基本功能,以及Web和Mail反向代理的功能;還用于啟用網(wǎng)絡(luò)協(xié)議,創(chuàng)建必要的運(yùn)行時(shí)環(huán)境以及確保不同的模塊之間平滑地進(jìn)行交互。不過(guò),大多跟協(xié)議相關(guān)的功能和某應(yīng)用特有的功能都是由nginx的模塊實(shí)現(xiàn)的。這些功能模塊大致可以分為事件模塊、階段性處理器、輸出過(guò)濾器、變量處理器、協(xié)議、upstream和負(fù)載均衡幾個(gè)類別,這些共同組成了nginx的http功能。事件模塊主要用于提供OS獨(dú)立的(不同操作系統(tǒng)的事件機(jī)制有所不同)事件通知機(jī)制如kqueue或epoll等。協(xié)議模塊則負(fù)責(zé)實(shí)現(xiàn)nginx通過(guò)http、tls/ssl、smtp、pop3以及imap與對(duì)應(yīng)的客戶端建立會(huì)話。
Nginx的核心模塊為Main和Events,此外還包括標(biāo)準(zhǔn)HTTP模塊、可選HTTP模塊和郵件模塊,其還可以支持諸多第三方模塊。Main用于配置錯(cuò)誤日志、進(jìn)程及權(quán)限等相關(guān)的參數(shù),Events用于配置IO模型,如epoll、kqueue、select或poll等,它們是必備模塊。
Nginx的主配置文件由幾個(gè)段組成,這個(gè)段通常也被稱為nginx的上下文,每個(gè)段的定義格式如下所示。需要注意的是,其每一個(gè)指令都必須使用分號(hào)(;)結(jié)束,否則為語(yǔ)法錯(cuò)誤。
<section> {
<directive> <parameters>;
}
2.1 配置main模塊
下面說(shuō)明main模塊中的幾個(gè)關(guān)鍵參數(shù)。
2.1.1 error_log
用于配置錯(cuò)誤日志,可用于main、http、server及l(fā)ocation上下文中;語(yǔ)法格式為:
error_log file | stderr [ debug | info | notice | warn | error | crit | alert | emerg ]
如果在編譯nginx時(shí)使用了--with-debug選項(xiàng),還可以使用如下格式打開(kāi)調(diào)試功能。
error_log LOGFILE [debug_core | debug_alloc | debug_mutex | debug_event | debug_http | debug_imap];
要禁用錯(cuò)誤日志,不能使用“error_log off;”,而要使用類似如下選項(xiàng):
error_log /dev/null crit;
2.1.2 timer_resolution
用于降低gettimeofday()系統(tǒng)調(diào)用的次數(shù)。默認(rèn)情況下,每次從kevent()、epoll、/dev/poll、select()或poll()返回時(shí)都會(huì)執(zhí)行此系統(tǒng)調(diào)用。語(yǔ)法格式為:
timer_resolution interval
例如:
timer_resolution 100ms;
2.1.3 worker_cpu_affinity
通過(guò)sched_setaffinity()將worker綁定至CPU上,只能用于main上下文。語(yǔ)法格式為:
worker_cpu_affinity cpumask ...
例如:
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
2.1.4 worker_priority
為worker進(jìn)程設(shè)定優(yōu)先級(jí)(指定nice值),此參數(shù)只能用于main上下文中,默認(rèn)為0;語(yǔ)法格式為:
worker_priority number
2.1.5 worker_processes
worker進(jìn)程是單線程進(jìn)程。如果Nginx用于CPU密集型的場(chǎng)景中,如SSL或gzip,且主機(jī)上的CPU個(gè)數(shù)至少有2個(gè),那么應(yīng)該將此參數(shù)值設(shè)定為與CPU核心數(shù)相同;如果Nginx用于大量靜態(tài)文件訪問(wèn)的場(chǎng)景中,且所有文件的總大小大于可用內(nèi)存時(shí),應(yīng)該將此參數(shù)的值設(shè)定得足夠大以充分利用磁盤(pán)帶寬。
此參數(shù)與Events上下文中的work_connections變量一起決定了maxclient的值:
maxclients = work_processes * work_connections
2.1.6 worker_rlimit_nofile
設(shè)定worker進(jìn)程所能夠打開(kāi)的文件描述符個(gè)數(shù)的最大值。語(yǔ)法格式:
worker_rlimit_nofile number
2.2 配置Events模塊
2.2.1 worker_connections
設(shè)定每個(gè)worker所處理的最大連接數(shù),它與來(lái)自main上下文的worker_processes一起決定了maxclients的值。
max clients = worker_processes * worker_connections
而在反向代理場(chǎng)景中,其計(jì)算方法與上述公式不同,因?yàn)槟J(rèn)情況下瀏覽器將打開(kāi)2個(gè)連接,而nginx會(huì)為每一個(gè)連接打開(kāi)2個(gè)文件描述符,因此,其maxclients的計(jì)算方法為:
max clients = worker_processes * worker_connections/4
2.2.2 use
在有著多于一個(gè)的事件模型IO的應(yīng)用場(chǎng)景中,可以使用此指令設(shè)定nginx所使用的IO機(jī)制,默認(rèn)為./configure腳本選定的各機(jī)制中最適用當(dāng)前OS的版本。語(yǔ)法格式:
use [ kqueue | rtsig | epoll | /dev/poll | select | poll | eventport ]
2.3 一個(gè)配置示例
user nginx;
# the load is CPU-bound and we have 16 cores
worker_processes 16;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
use epoll;
worker_connections 2048;
}
2.4 HTTP服務(wù)的相關(guān)配置
http上下文專用于配置用于http的各模塊,此類指令非常的多,每個(gè)模塊都有其專用指定,具體請(qǐng)參數(shù)nginx官方wiki關(guān)于模塊部分的說(shuō)明。大體上來(lái)講,這些模塊所提供的配置指令還可以分為如下幾個(gè)類別。
客戶端類指令:如client_body_buffer_size、client_header_buffer_size、client_header_timeout和keepalive_timeout等;
文件IO類指令:如aio、directio、open_file_cache、open_file_cache_min_uses、open_file_cache_valid和sendfile等;
hash類指令:用于定義Nginx為某特定的變量分配多大的內(nèi)存空間,如types_hash_bucket_size、server_names_hash_bucket_size和variables_hash_bucket_size等;
套接字類指令:用于定義Nginx如何處理tcp套接字相關(guān)的功能,如tcp_nodelay(用于keepalive功能啟用時(shí))和tcp_nopush(用于sendfile啟用時(shí))等;
2.5 虛擬服務(wù)器相關(guān)配置
server {
<directive> <parameters>;
}
用于定義虛擬服務(wù)器相關(guān)的屬性,常見(jiàn)的指令有backlog、rcvbuf、bind及sndbuf等。
2.6 location相關(guān)的配置
location [modifier] uri {...} 或 location @name {…}
通常用于server上下文中,用于設(shè)定某URI的訪問(wèn)屬性。location可以嵌套。
The prefix "@" specifies a named location. Such locations are not used during normal processing of requests, they are intended only to process internally redirected requests (see error_page, try_files). 如下面關(guān)于memcached的相關(guān)配置。
server {
location / {
set $memcached_key $uri;
memcached_pass name:11211;
default_type text/html;
error_page 404 @fallback;
}
location @fallback {
proxy_pass http://backend;
}
}
三、Nginx反向代理
Nginx通過(guò)proxy模塊實(shí)現(xiàn)反向代理功能。在作為web反向代理服務(wù)器時(shí),nginx負(fù)責(zé)接收客戶請(qǐng)求,并能夠根據(jù)URI、客戶端參數(shù)或其它的處理邏輯將用戶請(qǐng)求調(diào)度至上游服務(wù)器上(upstream server)。nginx在實(shí)現(xiàn)反向代理功能時(shí)的最重要指令為proxy_pass,它能夠?qū)ocation定義的某URI代理至指定的上游服務(wù)器(組)上。如下面的示例中,location的/uri將被替換為上游服務(wù)器上的/newuri。
location /uri {
proxy_pass http://www.zhongjima.net:8080/newuri;
}
不過(guò),這種處理機(jī)制中有兩個(gè)例外。一個(gè)是如果location的URI是通過(guò)模式匹配定義的,其URI將直接被傳遞至上游服務(wù)器,而不能為其指定轉(zhuǎn)換的另一個(gè)URI。例如下面示例中的/forum將被代理為http://www.zhongjima.net/forum。
location ~ ^/bbs {
proxy_pass http://www.zhongjima.net;
}
第二個(gè)例外是,如果在loation中使用的URL重定向,那么nginx將使用重定向后的URI處理請(qǐng)求,而不再考慮上游服務(wù)器上定義的URI。如下面所示的例子中,傳送給上游服務(wù)器的URI為/index.php?page=<match>,而不是/index。
location / {
rewrite /(.*)$ /index.php?page=$1 break;
proxy_pass http://localhost:8080/index;
}
3.1 proxy模塊的指令
proxy模塊的可用配置指令非常多,它們分別用于定義proxy模塊工作時(shí)的諸多屬性,如連接超時(shí)時(shí)長(zhǎng)、代理時(shí)使用http協(xié)議版本等。下面對(duì)常用的指令做一個(gè)簡(jiǎn)單說(shuō)明。
proxy_connect_timeout:nginx將一個(gè)請(qǐng)求發(fā)送至upstream server之前等待的最大時(shí)長(zhǎng);
proxy_cookie_domain:將upstream server通過(guò)Set-Cookie首部設(shè)定的domain屬性修改為指定的值,其值可以為一個(gè)字符串、正則表達(dá)式的模式或一個(gè)引用的變量;
proxy_cookie_path: 將upstream server通過(guò)Set-Cookie首部設(shè)定的path屬性修改為指定的值,其值可以為一個(gè)字符串、正則表達(dá)式的模式或一個(gè)引用的變量;
proxy_hide_header:設(shè)定發(fā)送給客戶端的報(bào)文中需要隱藏的首部;
proxy_pass:指定將請(qǐng)求代理至upstream server的URL路徑;
proxy_set_header:將發(fā)送至upsream server的報(bào)文的某首部進(jìn)行重寫(xiě);
proxy_redirect:重寫(xiě)location并刷新從upstream server收到的報(bào)文的首部;
proxy_send_timeout:在連接斷開(kāi)之前兩次發(fā)送至upstream server的寫(xiě)操作的最大間隔時(shí)長(zhǎng);
proxy_read_timeout:在連接斷開(kāi)之前兩次從接收upstream server接收讀操作的最大間隔時(shí)長(zhǎng);
如下面的一個(gè)示例:
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 30;
proxy_send_timeout 15;
proxy_read_timeout 15;
3.2 upstream模塊
與proxy模塊結(jié)合使用的模塊中,最常用的當(dāng)屬u(mài)pstream模塊。upstream模塊可定義一個(gè)新的上下文,它包含了一組寶島upstream服務(wù)器,這些服務(wù)器可能被賦予了不同的權(quán)重、不同的類型甚至可以基于維護(hù)等原因被標(biāo)記為down。
upstream模塊常用的指令有:
ip_hash:基于客戶端IP地址完成請(qǐng)求的分發(fā),它可以保證來(lái)自于同一個(gè)客戶端的請(qǐng)求始終被轉(zhuǎn)發(fā)至同一個(gè)upstream服務(wù)器;
keepalive:每個(gè)worker進(jìn)程為發(fā)送到upstream服務(wù)器的連接所緩存的個(gè)數(shù);
least_conn:最少連接調(diào)度算法;
server:定義一個(gè)upstream服務(wù)器的地址,還可包括一系列可選參數(shù),如:
weight:權(quán)重;
max_fails:最大失敗連接次數(shù),失敗連接的超時(shí)時(shí)長(zhǎng)由fail_timeout指定;
fail_timeout:等待請(qǐng)求的目標(biāo)服務(wù)器發(fā)送響應(yīng)的時(shí)長(zhǎng);
backup:用于fallback的目的,所有服務(wù)均故障時(shí)才啟動(dòng)此服務(wù)器;
down:手動(dòng)標(biāo)記其不再處理任何請(qǐng)求;
例如:
upstream backend {
server www.zhongjima.net weight=5;
server www2.amd5.cn:8080 max_fails=3 fail_timeout=30s;
}
upstream模塊的負(fù)載均衡算法主要有三種,輪調(diào)(round-robin)、ip哈希(ip_hash)和最少連接(least_conn)三種。
此外,upstream模塊也能為非http類的應(yīng)用實(shí)現(xiàn)負(fù)載均衡,如下面的示例定義了nginx為memcached服務(wù)實(shí)現(xiàn)負(fù)載均衡之目的。
upstream memcachesrvs {
server 172.16.100.6:11211;
server 172.16.100.7:11211;
}
server {
location / {
set $memcached_key "$uri?$args";
memcached_pass memcachesrvs;
error_page 404 = @fallback;
}
location @fallback {
proxy_pass http://127.0.0.1:8080;
}
}
3.3 if判斷語(yǔ)句
在location中使用if語(yǔ)句可以實(shí)現(xiàn)條件判斷,其通常有一個(gè)return語(yǔ)句,且一般與有著last或break標(biāo)記的rewrite規(guī)則一同使用。但其也可以按需要使用在多種場(chǎng)景下,需要注意的是,不當(dāng)?shù)氖褂每赡軙?huì)導(dǎo)致不可預(yù)料的后果。
location / {
if ($request_method == “PUT”) {
proxy_pass http://upload.amd5.cn:8080;
}
if ($request_uri ~ "\.(jpg|gif|jpeg|png)$") {
proxy_pass http://imageservers;
break;
}
}
upstream imageservers {
server 172.16.100.8:80 weight 2;
server 172.16.100.9:80 weight 3;
}
3.3.1 if語(yǔ)句中的判斷條件
正則表達(dá)式匹配:
~:與指定正則表達(dá)式模式匹配時(shí)返回“真”,判斷匹配與否時(shí)區(qū)分字符大小寫(xiě);
~*:與指定正則表達(dá)式模式匹配時(shí)返回“真”,判斷匹配與否時(shí)不區(qū)分字符大小寫(xiě);
!~:與指定正則表達(dá)式模式不匹配時(shí)返回“真”,判斷匹配與否時(shí)區(qū)分字符大小寫(xiě);
!~*:與指定正則表達(dá)式模式不匹配時(shí)返回“真”,判斷匹配與否時(shí)不區(qū)分字符大小寫(xiě);
文件及目錄匹配判斷:
-f, !-f:判斷指定的路徑是否為存在且為文件;
-d, !-d:判斷指定的路徑是否為存在且為目錄;
-e, !-e:判斷指定的路徑是否存在,文件或目錄均可;
-x, !-x:判斷指定路徑的文件是否存在且可執(zhí)行;
3.3.2 nginx常用的全局變量
下面是nginx常用的全局變量中的一部分,它們經(jīng)常用于if語(yǔ)句中實(shí)現(xiàn)條件判斷。
$args
$content_length
$content_type
$document_root
$document_uri
$host
$http_user_agent
$http_cookie
$limit_rate
$request_body_file
$request_method
$remote_addr
$remote_port
$remote_user
$request_filename
$request_uri
$query_string
$scheme
$server_protocol
$server_addr
$server_name
$server_port
$uri
四、反向代理性能優(yōu)化
在反向代理場(chǎng)景中,nginx有一系列指令可用于定義其工作特性,如緩沖區(qū)大小等,給這些指令設(shè)定一個(gè)合理的值,可以有效提升其性能。
4.1 緩沖區(qū)設(shè)定
nginx在默認(rèn)情況下在將其響應(yīng)給客戶端之前會(huì)盡可能地接收來(lái)upstream服務(wù)器的響應(yīng)報(bào)文,它會(huì)將這些響應(yīng)報(bào)文存暫存于本地并盡量一次性地響應(yīng)給客戶端。然而,在來(lái)自于客戶端的請(qǐng)求或來(lái)自u(píng)psteam服務(wù)器的響應(yīng)過(guò)多時(shí),nginx會(huì)試圖將之存儲(chǔ)于本地磁盤(pán)中,這將大大降低nginx的性能。因此,在有著更多可用內(nèi)存的場(chǎng)景中,應(yīng)該將用于暫存這些報(bào)文的緩沖區(qū)調(diào)大至一個(gè)合理的值。
proxy_buffer_size size:設(shè)定用于暫存來(lái)自于upsteam服務(wù)器的第一個(gè)響應(yīng)報(bào)文的緩沖區(qū)大?。?/span>
proxy_buffering on|off:?jiǎn)⒂镁彌_upstream服務(wù)器的響應(yīng)報(bào)文,否則,如果proxy_max_temp_file_size指令的值為0,來(lái)自u(píng)pstream服務(wù)器的響應(yīng)報(bào)文在接收到的那一刻將同步發(fā)送至客戶端;一般情況下,啟用proxy_buffering并將proxy_max_temp_file_size設(shè)定為0能夠啟用緩存響應(yīng)報(bào)文的功能,并能夠避免將其緩存至磁盤(pán)中;
proxy_buffers 8 4k|8k:用于緩沖來(lái)自u(píng)pstream服務(wù)器的響應(yīng)報(bào)文的緩沖區(qū)大?。?/span>
4.2 緩存
nginx做為反向代理時(shí),能夠?qū)?lái)自u(píng)pstream的響應(yīng)緩存至本地,并在后續(xù)的客戶端請(qǐng)求同樣內(nèi)容時(shí)直接從本地構(gòu)造響應(yīng)報(bào)文。
proxy_cache zone|off:定義一個(gè)用于緩存的共享內(nèi)存區(qū)域,其可被多個(gè)地方調(diào)用;緩存將遵從upstream服務(wù)器的響應(yīng)報(bào)文首部中關(guān)于緩存的設(shè)定,如 "Expires"、"Cache-Control: no-cache"、 "Cache-Control: max-age=XXX"、"private"和"no-store" 等,但nginx在緩存時(shí)不會(huì)考慮響應(yīng)報(bào)文的"Vary"首部。為了確保私有信息不被緩存,所有關(guān)于用戶的私有信息可以u(píng)pstream上通過(guò)"no-cache" or "max-age=0"來(lái)實(shí)現(xiàn),也可在nginx設(shè)定proxy_cache_key必須包含用戶特有數(shù)據(jù)如$cookie_xxx的方式實(shí)現(xiàn),但最后這種方式在公共緩存上使用可能會(huì)有風(fēng)險(xiǎn)。因此,在響應(yīng)報(bào)文中含有以下首部或指定標(biāo)志的報(bào)文將不會(huì)被緩存。
Set-Cookie
Cache-Control containing "no-cache", "no-store", "private", or a "max-age" with a non-numeric or 0 value
Expires with a time in the past
X-Accel-Expires: 0
proxy_cache_key:設(shè)定在存儲(chǔ)及檢索緩存時(shí)用于“鍵”的字符串,可以使用變量為其值,但使用不當(dāng)時(shí)有可能會(huì)為同一個(gè)內(nèi)容緩存多次;另外,將用戶私有信息用于鍵可以避免將用戶的私有信息返回給其它用戶;
proxy_cache_lock:?jiǎn)⒂么隧?xiàng),可在緩存未命令中阻止多個(gè)相同的請(qǐng)求同時(shí)發(fā)往upstream,其生效范圍為worker級(jí)別;
proxy_cache_lock_timeout:proxy_cache_lock功能的鎖定時(shí)長(zhǎng);
proxy_cache_min_uses:某響應(yīng)報(bào)文被緩存之前至少應(yīng)該被請(qǐng)求的次數(shù);
proxy_cache_path:定義一個(gè)用記保存緩存響應(yīng)報(bào)文的目錄,及一個(gè)保存緩存對(duì)象的鍵及響應(yīng)元數(shù)據(jù)的共享內(nèi)存區(qū)域(keys_zone=name:size),其可選參數(shù)有:
levels:每級(jí)子目錄名稱的長(zhǎng)度,有效值為1或2,每級(jí)之間使用冒號(hào)分隔,最多為3級(jí);
inactive:非活動(dòng)緩存項(xiàng)從緩存中剔除之前的最大緩存時(shí)長(zhǎng);
max_size:緩存空間大小的上限,當(dāng)需要緩存的對(duì)象超出此空間限定時(shí),緩存管理器將基于LRU算法對(duì)其進(jìn)行清理;
loader_files:緩存加載器(cache_loader)的每次工作過(guò)程最多為多少個(gè)文件加載元數(shù)據(jù);
loader_sleep:緩存加載器的每次迭代工作之后的睡眠時(shí)長(zhǎng);
loader_threashold:緩存加載器的最大睡眠時(shí)長(zhǎng);
例如: proxy_cache_path /data/nginx/cache/one levels=1 keys_zone=one:10m;
proxy_cache_path /data/nginx/cache/two levels=2:2 keys_zone=two:100m;
proxy_cache_path /data/nginx/cache/three levels=1:1:2 keys_zone=three:1000m;
proxy_cache_use_stale:在無(wú)法聯(lián)系到upstream服務(wù)器時(shí)的哪種情形下(如error、timeout或http_500等)讓nginx使用本地緩存的過(guò)期的緩存對(duì)象直接響應(yīng)客戶端請(qǐng)求;其格式為:
proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_404 | off
proxy_cache_valid [ code ...] time:用于為不同的響應(yīng)設(shè)定不同時(shí)長(zhǎng)的有效緩存時(shí)長(zhǎng),例如:proxy_cache_valid 200 302 10m;
proxy_cache_methods [GET HEAD POST]:為哪些請(qǐng)求方法啟用緩存功能;
proxy_cache_bypass string:設(shè)定在哪種情形下,nginx將不從緩存中取數(shù)據(jù);例如:
proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;
proxy_cache_bypass $http_pragma $http_authorization;
4.2.1 使用示例
http {
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=STATIC:10m
inactive=24h max_size=1g;
server {
location / {
proxy_pass http://www.zhongjima.net;
proxy_set_header Host $host;
proxy_cache STATIC;
proxy_cache_valid 200 1d;
proxy_cache_valid 301 302 10m;
proxy_cache_vaild any 1m;
proxy_cache_use_stale error timeout invalid_header updating
http_500 http_502 http_503 http_504;
}
}
}
4.3 壓縮
nginx將響應(yīng)報(bào)文發(fā)送至客戶端之前可以啟用壓縮功能,這能夠有效地節(jié)約帶寬,并提高響應(yīng)至客戶端的速度。通常編譯nginx默認(rèn)會(huì)附帶gzip壓縮的功能,因此,可以直接啟用之。
http {
gzip on;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript application/json;
gzip_disable msie6;
}
gzip_proxied指令可以定義對(duì)客戶端請(qǐng)求哪類對(duì)象啟用壓縮功能,如“expired”表示對(duì)由于使用了expire首部定義而無(wú)法緩存的對(duì)象啟用壓縮功能,其它可接受的值還有“no-cache”、“no-store”、“private”、“no_last_modified”、“no_etag”和“auth”等,而“off”則表示關(guān)閉壓縮功能。
五、配置示例
5.1 反向代理
server {
listen 80;
server_name www.zhongjima.net;
add_header X-Via $server_addr;
location / {
root html;
index index.html index.htm;
if ($request_method ~* "PUT") {
proxy_pass http://172.16.100.12;
break;
}
}
location /bbs {
proxy_pass http://172.16.100.11/;
}
}
此例中,對(duì)http://www.zhongjima.net/bbs/的請(qǐng)求將被轉(zhuǎn)發(fā)至http://172.16.100.11/這個(gè)URL,切記最后的/不應(yīng)該省去;而/匹配的URL中請(qǐng)求方法為“PUT”時(shí),將被轉(zhuǎn)發(fā)至http://172.16.100.12/這個(gè)URL。
另外,add_header用于讓nginx在響應(yīng)給用戶的報(bào)文中構(gòu)造自定義首部,其使用格式為“add_header NAME VALUE”。
可以使用curl命令對(duì)配置好的服務(wù)進(jìn)行請(qǐng)求,以驗(yàn)正其效果。如:
# curl -I http://www.zhongjima.net/bbs/
HTTP/1.1 200 OK
Server: nginx/1.4.1
Date: Tue, 14 May 2013 10:19:10 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 15
Connection: keep-alive
Last-Modified: Tue, 30 Apr 2013 09:34:09 GMT
ETag: "186e9f-f-b4076640"
X-Via: 172.16.100.107
Accept-Ranges: bytes
在后端服務(wù)器172.16.100.12上裝載dav模塊,并開(kāi)放其dav功能,而后驗(yàn)正文件上傳效果。開(kāi)放dav功能的方法如下:
首先啟用如下兩個(gè)模塊:
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
而后配置相應(yīng)主機(jī)的目錄如下所示,關(guān)鍵是其中的dav一行。
<Directory "/var/www/html">
dav on
Options Indexes FollowSymLinks
Order allow,deny
Allow from all
</Directory>
接著嘗試訪問(wèn)代理服務(wù)器:
# curl -I -T /etc/inittab http://www.zhongjima.net/
HTTP/1.1 100 Continue
HTTP/1.1 201 Created
Server: nginx/1.4.1
Date: Tue, 14 May 2013 10:20:15 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 261
Location: http://172.16.100.107/inittab
Connection: keep-alive
X-Via: 172.16.100.107
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>201 Created</title>
</head><body>
<h1>Created</h1>
<p>Resource /inittab has been created.</p>
<hr />
<address>Apache/2.2.3 (Red Hat) Server at 172.16.100.12 Port 80</address>
</body></html>
5.2 啟用緩存
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
proxy_cache_path /nginx/cache/first levels=1:2 keys_zone=first:10m max_size=512m;
server {
listen 80;
server_name www.zhongjima.net;
location / {
root html;
index index.html index.htm;
if ($request_method ~* "PUT") {
proxy_pass http://172.16.100.12;
break;
}
}
location /bbs {
proxy_pass http://172.16.100.11/;
proxy_cache first;
proxy_cache_valid 200 1d;
proxy_cache_valid 301 302 10m;
proxy_cache_valid any 1m;
}
}
}
5.3 使用upstream
5.3.1 不啟用緩存
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream websrv {
server 172.16.100.11 weight=1;
server 172.16.100.12 weight=1;
server 127.0.0.1:8080 backup;
}
server {
listen 80;
server_name www.zhongjima.net;
add_header X-Via $server_addr;
location / {
proxy_pass http://websrv;
index index.html index.htm;
if ($request_method ~* "PUT") {
proxy_pass http://172.16.100.12;
break;
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 8080;
server_name localhost;
root /nginx/htdocs;
index index.html;
}
}
測(cè)試效果:默認(rèn)情況下,nginx對(duì)定義了權(quán)重的upstream服務(wù)器使用加權(quán)輪調(diào)的方法調(diào)度訪問(wèn),因此,其多次訪問(wèn)應(yīng)該由不同的服務(wù)器進(jìn)行響應(yīng)。如下所示。
# curl http://172.16.100.107/
RS2.amd5.cn
# curl http://172.16.100.107/
RS1.amd5.cn
根據(jù)上面的配置,如果172.16.100.11和172.16.100.12兩個(gè)upstream服務(wù)器均宕機(jī)時(shí),將由本地監(jiān)聽(tīng)在8080端口的虛擬主機(jī)進(jìn)行響應(yīng)。
# curl http://172.16.100.107/
Sorry...
5.3.2 為upstream啟用緩存
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
proxy_cache_path /nginx/cache/first levels=1:2 keys_zone=first:10m max_size=512m;
upstream websrv {
server 172.16.100.11 weight=1;
server 172.16.100.12 weight=1;
server 127.0.0.1:8080 backup;
}
server {
listen 80;
server_name www.zhongjima.net;
add_header X-Via $server_addr;
add_header X-Cache-Status $upstream_cache_status;
location / {
proxy_pass http://websrv;
proxy_cache first;
proxy_cache_valid 200 1d;
proxy_cache_valid 301 302 10m;
proxy_cache_valid any 1m;
index index.html index.htm;
if ($request_method ~* "PUT") {
proxy_pass http://172.16.100.12;
break;
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 8080;
server_name localhost;
root /nginx/htdocs;
index index.html;
}
}
第一次訪問(wèn)某可緩存資源時(shí),在本地緩存中尚未有其對(duì)應(yīng)的緩存對(duì)象,因此,其一定為未命中狀態(tài)。而第二次請(qǐng)求時(shí),則可以直接從本地緩存構(gòu)建響應(yīng)報(bào)文。
# curl -I http://www.zhongjima.net/
HTTP/1.1 200 OK
Server: nginx/1.4.1
Date: Tue, 14 May 2013 10:53:07 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 15
Connection: keep-alive
Last-Modified: Tue, 30 Apr 2013 09:34:09 GMT
ETag: "186e9f-f-b4076640"
Accept-Ranges: bytes
X-Via: 172.16.100.107
X-Cache-Status: MISS
# curl -I http://www.zhongjima.net/
HTTP/1.1 200 OK
Server: nginx/1.4.1
Date: Tue, 14 May 2013 10:53:09 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 15
Connection: keep-alive
Last-Modified: Tue, 30 Apr 2013 09:34:09 GMT
ETag: "186e9f-f-b4076640"
X-Via: 172.16.100.107
X-Cache-Status: HIT
Accept-Ranges: bytes