Nginx中文手冊

Nginx中文手冊


1、 Nginx 基礎知識
2、 Nginx 安裝及調試
3、 Nginx Rewrite
4、 Nginx Redirect
5、 Nginx 目錄自動加斜線:
6、 Nginx Location
7、 Nginx expires
8、 Nginx 防盜鏈
9、 Nginx 訪問控制
10、 Nginx日誌處理
11、 Nginx Cache
12、 Nginx 負載均衡
十3、 Nginx簡單優化
十4、 如何構建高性能的LEMP環境
十5、 Nginx服務監控
十6、 常見問題與錯誤處理.
十7、 相關資源下載javascript

【前言】:php

編寫此技術指南在於推廣普及NGINX在國內的使用,更方便的幫助你們瞭解和掌握NGINX
的一些使用技巧。本指南不少技巧來自於網絡和工做中或網絡上朋友們問個人問題.在此對
網絡上願意分享的朋友們表示感謝和致意!歡迎你們和我一塊兒豐富本技術指南提出更好的建
議!請朋友們關注: http://www.linuxtone.org 技術分享社區! 互想學習共同進步!css

1、 Nginx 基礎知識html

一、簡介
Nginx ("engine x") 是一個高性能的 HTTP 和 反向代理 服務器,也是一個 IMAP/POP3/SMTP java

代理服
務器。 Nginx 是由 Igor Sysoev 爲俄羅斯訪問量第二的 Rambler.ru 站點開發的,它已經在該node

站點運行超
過兩年半了。Igor 將源代碼以類BSD許可證的形式發佈。儘管仍是測試版,可是,Nginx 已經mysql

由於它的穩
定性、豐富的功能集、示例配置文件和低系統資源的消耗而聞名了。linux

更多的請見官方wiki: http://wiki.codemongers.com/nginx

二、 Nginx的優勢
nginx作爲HTTP服務器,有如下幾項基本特性:
1) 處理靜態文件,索引文件以及自動索引;打開文件描述符緩衝.
2) 無緩存的反向代理加速,簡單的負載均衡和容錯.
3) FastCGI,簡單的負載均衡和容錯.
4) 模塊化的結構。包括gzipping, byte ranges, chunked responses, 以及 SSI-filter等filter。
若是由FastCGI或其它代理服務器處理單頁中存在的多個SSI,則這項處理能夠並行運行,而不
須要相互等待。
5) 支持SSL 和 TLS SNI.
Nginx專爲性能優化而開發,性能是其最重要的考量, 實現上很是注重效率 。它支持內核Poll模web

型,
能經受高負載的考驗, 有報告代表能支持高達 50,000 個併發鏈接數。

Nginx具備很高的穩定性。其它HTTP服務器,當遇到訪問的峯值,或者有人惡意發起慢速鏈接

時,
也極可能會致使服務器物理內存耗盡頻繁交換,失去響應,只能重啓服務器。例如當前apache

一旦上到
200個以上進程,web響應速度就明顯很是緩慢了。而Nginx採起了分階段資源分配技術,使得

它的CPU與
內存佔用率很是低。nginx官方表示保持10,000個沒有活動的鏈接,它只佔2.5M內存,因此類

似DOS這
樣的攻擊對nginx來講基本上是毫無用處的。就穩定性而言, nginx比lighthttpd更勝一籌。

Nginx支持熱部署。它的啓動特別容易, 而且幾乎能夠作到7*24不間斷運行,即便運行數個月

也不
須要從新啓動。你還可以在不間斷服務的狀況下,對軟件版本進行進行升級。

Nginx採用master-slave模型, 可以充分利用SMP的優點,且可以減小工做進程在磁盤I/O的阻
塞延遲。當採用select()/poll()調用時,還能夠限制每一個進程的鏈接數。

Nginx代碼質量很是高,代碼很規範, 手法成熟, 模塊擴展也很容易。特別值得一提的是強大
的Upstream與Filter鏈。 Upstream爲諸如reverse proxy, 與其餘服務器通訊模塊的編寫奠基了

很好的
基礎。而Filter鏈最酷的部分就是各個filter沒必要等待前一個filter執行完畢。它能夠把前一個filter
的輸出作爲當前filter的輸入,這有點像Unix的管線。這意味着,一個模塊能夠開始壓縮從後端

服務器
發送過來的請求,且能夠在模塊接收完後端服務器的整個請求以前把壓縮流轉向客戶端。

Nginx採用了一些os提供的最新特性如對sendfile (Linux 2.2+),accept-filter (FreeBSD
4.1+),TCP_DEFER_ACCEPT (Linux 2.4+) 的支持,從而大大提升了性能

2、 Nginx 安裝及調試

一、Pcre 安裝

./configure
make && make install
cd ../
2. nginx 編譯安裝

/configure --user=www --group=www --prefix=/usr/local/nginx/ --with-

http_stub_status_module
--with-openssl=/usr/local/openssl

make && make install
更詳細的模塊定製與安裝請參照官方wiki.

三、Nginx 配置文件測試:

# /usr/local/nginx/sbin/nginx -t //Debug 配置文件的關鍵命令須要重點撐握.
2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf
syntax is ok
2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf

was
tested successfully

三、 Nginx 啓動:

# /usr/local/nginx/sbin/nginx
四、 Nginx 配置文件修改從新加載:

# kill -HUP `cat /usr/local/nginx/logs/nginx.pid `
3、 Nginx Rewrite

1. Nginx Rewrite 基本標記(flags)
last - 基本上都用這個Flag。
※至關於Apache裏的[L]標記,表示完成rewrite,再也不匹配後面的規則
break - 停止Rewirte,再也不繼續匹配
redirect - 返回臨時重定向的HTTP狀態302
permanent - 返回永久重定向的HTTP狀態301
※原有的url支持正則 重寫的url不支持正則

2. 正則表達式匹配,其中:
~ 爲區分大小寫匹配
~* 爲不區分大小寫匹配
!~ 和 !~* 分別爲區分大小寫不匹配及不區分大小寫不匹配

3. 文件及目錄匹配,其中:
-f 和 !-f 用來判斷是否存在文件
-d 和 !-d 用來判斷是否存在目錄
-e 和 !-e 用來判斷是否存在文件或目錄
-x 和 !-x 用來判斷文件是否可執行

3. Nginx 的一些可用的全局變量,可用作條件判斷:

$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
4、 Nginx Redirect

將全部linuxtone.org與netseek.linuxtone.org域名所有自跳轉到http://www.linuxtone.org

server {
    listen 80;
    server_name linuxtone.org netseek.linuxtone.org;
    index index.html index.php;
    root /data/www/wwwroot;
    if ($host !~ "^www\.linxtone\.org$") {
        rewrite ^(.*) http://www.linuxtone.org$1 redirect;
    }
    .....................
}
5、 Nginx 目錄自動加斜線:

if (-d $request_filename){
    rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
6、 Nginx Location

1.基本語法:[和上面rewrite正則匹配語法基本一致]
location [=|~|~*|^~] /uri/ { … }
~ 爲區分大小寫匹配
~* 爲不區分大小寫匹配
!~ 和 !~* 分別爲區分大小寫不匹配及不區分大小寫不匹配

示例1:

location = / {
    # matches the query / only.
    # 只匹配 / 查詢。
}
匹配任何查詢,由於全部請求都已 / 開頭。可是正則表達式規則和長的塊規則將被優先和查詢

匹配

示例2:

location ^~ /images/ {
    # matches any query beginning with /images/ and halts searching,
    # so regular expressions will not be checked.
    # 匹配任何以 /images/ 開頭的任何查詢而且中止搜索。任何正則表達式將不會被測試。
}
示例3:

location ~* \.(gif|jpg|jpeg)$ {
    # matches any request ending in gif, jpg, or jpeg. However, all
    # requests to the /images/ directory will be handled by
    # 匹配任何以 gif、jpg 或 jpeg 結尾的請求。
}
7、 Nginx expires

1.根據文件類型判斷,添加expires

# Add expires header for static content
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
    if (-f $request_filename) {
        root /data/www/wwwroot/bbs;
        expires 1d;
        break;
    }
}
二、根據某個目錄判斷,添加expires

# serve static files
location ~ ^/(images|JavaScript|js|css|flash|media|static)/ {
    root /data/www/wwwroot/down;
    expires 30d;
}
8、 Nginx 防盜鏈

1. 針對不一樣的文件類型

#Preventing hot linking of images and other file types
location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {
    valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost

baidu.com;
    if ($invalid_referer) {
        rewrite ^/ http://www.linuxtone.org/images/default/logo.gif;
        # return 403;
    }
}
2. 針對不一樣的目錄

location /img/ {
    root /data/www/wwwroot/bbs/img/;
    valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;
    if ($invalid_referer) {
        rewrite ^/ http://www.linuxtone.org/images/default/logo.gif;
        #return 403;
    }
}
3. 同實現防盜鏈和expires的方法

#Preventing hot linking of images and other file types
location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {
    valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost ;
    if ($invalid_referer) {
        rewrite ^/ http://www.linuxtone.org/images/default/logo.gif;
    }
    access_log off;
    root /data/www/wwwroot/bbs;
    expires 1d;
    break;
}
9、 Nginx 訪問控制

1. Nginx 身份證驗證

#cd /usr/local/nginx/conf
#mkdir htpasswd
/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone
#添加用戶名爲linuxtone
New password: (此處輸入你的密碼)
Re-type new password: (再次輸入你的密碼)
Adding password for user

http://count.linuxtone.org/tongji/data/index.html(目錄存在/data/www/wwwroot/tongji/data/

目錄

下)

將下段配置放到虛擬主機目錄,當訪問http://count.linuxtone/tongji/即提示要密驗證:

location ~ ^/(tongji)/ {
    root /data/www/wwwroot/count;
    auth_basic "LT-COUNT-TongJi";
    auth_basic_user_file /usr/local/nginx/conf/htpasswd/tongji;
}
2. Nginx 禁止訪問某類型的文件.

如,Nginx下禁止訪問*.txt文件,配置方法以下.

location ~* \.(txt|doc)$ {
    if (-f $request_filename) {
        root /data/www/wwwroot/linuxtone/test;
        #rewrite …..能夠重定向到某個URL
        break;
    }
}
方法2:

location ~* \.(txt|doc)${
    root /data/www/wwwroot/linuxtone/test;
    deny all;
}
實例:
禁止訪問某個目錄

location ~ ^/(WEB-INF)/ {
    deny all;
}
3. 使用ngx_http_access_module限制ip訪問

location / {
    deny 192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    deny all;
}
詳細參見wiki: http://wiki.codemongers.com/NginxHttpAccessModule#allow

4. Nginx 下載限制併發和速率

limit_zone linuxtone $binary_remote_addr 10m;
server {
    listen 80;
    server_name down.linuxotne.org;
    index index.html index.htm index.php;
    root /data/www/wwwroot/down;
    #Zone limit
    location / {
        limit_conn linuxtone 1;
        limit_rate 20k;
    }
    ..........
}
只容許客房端一個線程,每一個線程20k.

【注】limit_zone linuxtone $binary_remote_addr 10m; 這個能夠定義在主的

5. Nginx 實現Apache同樣目錄列表

location / {
    autoindex on;
}
6. 上文件大小限制
主配置文件里加入以下,具體大小根據你本身的業務作調整。

client_max_body_size 10m;
10、 Nginx 日誌處理

1.Nginx 日誌切割

#contab -e
59 23 * * * /usr/local/sbin/logcron.sh /dev/null 2>&1
# cat /usr/local/sbin/logcron.sh

#!/bin/bash

log_dir="/data/logs"

time=`date +%Y%m%d`

/bin/mv ${log_dir}/access_linuxtone.org.log 

${log_dir}/access_count.linuxtone.org.$time.logkill -USR1 `cat /var/run/nginx.pid`
更多的日誌分析與處理就關注(同時歡迎你參加討論):http://bbs.linuxtone.org/forum-8-1.html

2.利用AWSTATS分析NGINX日誌
設置好Nginx日誌格式,仍後利用awstats進行分析.
請參考: http://bbs.linuxtone.org/thread-56-1-1.html

3. Nginx 如何不記錄部分日誌
日誌太多,天天好幾個G,少記錄一些,下面的配置寫到server{}段中就能夠了

location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {
    access_log off;
}
11、Nginx Cache服務配置

若是須要將文件緩存到本地,則須要增長以下幾個子參數:

proxy_store on;
proxy_store_access user:rw group:rw all:rw;
proxy_temp_path 緩存目錄;
其中,
proxy_store on 用來啓用緩存到本地的功能,
proxy_temp_path 用來指定緩存在哪一個目錄下,如:proxy_temp_path html;

在通過上一步配置以後,雖然文件被緩存到了本地磁盤上,但每次請求仍會向遠端拉取
文件,爲了不去遠端拉取文件,必須修改proxy_pass:

if ( !-e $request_filename) {
    proxy_pass http://mysvr;
}
即改爲有條件地去執行proxy_pass,這個條件就是當請求的文件在本地的
proxy_temp_path指定的目錄下不存在時,再向後端拉取。

更多更高級的應用能夠研究ncache,官方網站: http://code.google.com/p/ncache/

詳細安裝請參照http://bbs.linuxtone.org 應用加速版ncache相關的貼子.

12、Nginx 負載均衡

1. Nginx 負載均衡基礎知識

nginx的upstream目前支持4種方式的分配

1)、輪詢(默認)
每一個請求按時間順序逐一分配到不一樣的後端服務器,若是後端服務器down掉,能自動剔除。

2)、weight
指定輪詢概率,weight和訪問比率成正比,用於後端服務器性能不均的狀況。

2)、ip_hash
每一個請求按訪問ip的hash結果分配,這樣每一個訪客固定訪問一個後端服務器,能夠解決session

的問題。

3)、fair(第三方)
按後端服務器的響應時間來分配請求,響應時間短的優先分配。

4)、url_hash(第三方)

2. Nginx 負載均衡實例1

upstream bbs.linuxtone.org { #定義負載均衡設備的Ip及設備狀態
    server 127.0.0.1:9090 down;
     server 127.0.0.1:8080 weight=2;
     server 127.0.0.1:6060;
     server 127.0.0.1:7070 backup;
}
在須要使用負載均衡的server中增長

proxy_pass http://bbs.linuxtone.org/;
每一個設備的狀態設置爲:
a) down 表示單前的server暫時不參與負載
b) weight 默認爲1.weight越大,負載的權重就越大。
c) max_fails :容許請求失敗的次數默認爲1.當超過最大次數時,返回proxy_next_upstream 

模塊定義的錯誤
d) fail_timeout:max_fails次失敗後,暫停的時間。
e) backup: 其它全部的非backup機器down或者忙的時候,請求backup機器。因此這臺機器

壓力會最輕。

nginx支持同時設置多組的負載均衡,用來給不用的server來使用。

client_body_in_file_only 設置爲On 能夠講client post過來的數據記錄到文件中用來作debug
client_body_temp_path 設置記錄文件的目錄 能夠設置最多3層目錄
location 對URL進行匹配.能夠進行重定向或者進行新的代理 負載均衡

3. Nginx 負載均衡實例 2
按訪問url的hash結果來分配請求,使每一個url定向到同一個後端服務器,後端服務器爲緩
存時比較有效,也能夠用做提升Squid緩存命中率.

簡單的負載均等實例:
#vi nginx.conf //nginx主配置文件核心配置
.........

#loadblance my.linuxtone.org
upstream my.linuxtone.org {
    ip_hash;
    server 127.0.0.1:8080;
    server 192.168.169.136:8080;
    server 219.101.75.138:8080;
    server 192.168.169.117;
    server 192.168.169.118;
    server 192.168.169.119;
}
.........
include vhosts/linuxtone_lb.conf;
.........
# vi proxy.conf

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 50m;
client_body_buffer_size 256k;
proxy_connect_timeout 30;
proxy_send_timeout 30;
proxy_read_timeout 60;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
proxy_max_temp_file_size 128m;
proxy_store on;
proxy_store_access user:rw group:rw all:r;
#nginx cache
#client_body_temp_path /data/nginx_cache/client_body 1 2;
proxy_temp_path /data/nginx_cache/proxy_temp 1 2;
#vi linuxtone_lb.conf

server {

    listen 80;
    server_name my.linuxtone.org;
    index index.php;
    root /data/www/wwwroot/mylinuxtone;

    if (-f $request_filename) {
        break;
    }

    if (-f $request_filename/index.php) {
        rewrite (.*) $1/index.php break;
    }

    error_page 403 http://my.linuxtone.org/member.php?m=user&a=login;

    location / {
        if ( !-e $request_filename) {
            proxy_pass http://my.linuxtone.org;
            break;
        }
        include /usr/local/nginx/conf/proxy.conf;
    }
}
十3、Nginx簡單優化

1. 減少nginx編譯後的文件大小 (Reduce file size of nginx)
默認的nginx編譯選項裏竟然是用debug模式(-g)的(debug模式會插入不少跟蹤和
ASSERT之類),編譯之後一個nginx有好幾兆。去掉nginx的debug模式編譯,編譯以
後只有幾百K

在 auto/cc/gcc,最後幾行有:

# debug
CFLAGS=」$CFLAGS -g」
註釋掉或刪掉這幾行,從新編譯便可。

2. 修改Nginx的header假裝服務器

1) 修改nginx.h

#vi nginx-0.7.30/src/core/nginx.h
#define NGINX_VERSION "1.8"
#define NGINX_VER "LTWS/" NGINX_VERSION
#define NGINX_VAR "NGINX"
#define NGX_OLDPID_EXT ".oldbin"
2) 修改nginx_http_header_filter_module
#vi nginx-0.7.30/src/http/ngx_http_header_filter_module.c
將以下

static char ngx_http_server_string[] = "Server: nginx" CRLF;
修改成

static char ngx_http_server_string[] = "Server: LTWS" CRLF;
a) 修改nginx_http_header_filter_module
#vi nginx-0.7.30/src/http/ngx_http_special_response.c
將以下:

static u_char ngx_http_error_full_tail[] =

--------------------------------------------------------------------------------

" NGINX_VER "
" CRLF
"" CRLF
"" CRLF
;

static u_char ngx_http_error_tail[] =

--------------------------------------------------------------------------------

nginx
" CRLF
"" CRLF
"" CRLF
;
修改成:

static u_char ngx_http_error_full_tail[] =

"NGINX_VER"
" CRLF

--------------------------------------------------------------------------------

http://www.linuxtone.org
" CRLF
"" CRLF
"" CRLF
;

static u_char ngx_http_error_tail[] =

--------------------------------------------------------------------------------

LTWS
" CRLF
"" CRLF
"" CRLF
;
修改後從新編譯一下環境,

404錯誤的時候顯示效果圖(若是沒有指定錯誤頁的話):

利用curl命令查看服務器header

3. 爲特定的CPU指定CPU類型編譯優化.

默認nginx使用的GCC編譯參數是-O

須要更加優化可使用如下兩個參數

--with-cc-opt='-O3' \

--with-cpu-opt=opteron \
使得編譯針對特定CPU以及增長GCC的優化.

此方法僅對性能有所改善並不會有很大的性能提高,供朋友們參考.

CPUD類型肯定:

# cat /proc/cpuinfo | grep "model name"
編譯優化參數參考:http://en.gentoo-wiki.com/wiki/Safe_Cflags

4. Tcmalloc優化Nginx 性能

# wget http://download.savannah.gnu.org/releases/libunwind/libunwind-0.99-alpha.tar.gz
# tar zxvf libunwind-0.99-alpha.tar.gz
# cd libunwind-0.99-alpha/
# CFLAGS=-fPIC ./configure
# make CFLAGS=-fPIC
# make CFLAGS=-fPIC install
# wget http://google-perftools.googlecode.com/files/google-perftools-0.98.tar.gz
# tar zxvf google-perftools-0.98.tar.gz
# cd google-perftools-0.98/
# ./configure
# make && make install
# echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
# ldconfig
# lsof -n | grep tcmalloc
編譯nginx 加載google_perftools_module:

./configure --with-google_perftools_module
在主配置文件加入nginx.conf 添加:

google_perftools_profiles /path/to/profile;
5. 內核參數優化
# vi /etc/sysctl.conf

#在末尾增長如下內容:
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 5000 65000
#使配置當即生效
/sbin/sysctl -p

十4、如何構建高性的LEMP

請參見: http://www.linuxtone.org/lemp/lemp.pdf

一、提供完整的配置腳本下載:http://www.linuxtone.org/lemp/scripts.tar.gz
二、提供NGINX常見配置範例含(虛擬主機,防盜鏈,Rewrite,訪問控制,負載均衡Discuz相關

程序靜態化及等等),你只要稍稍修改便可線上應用。
三、將原版的xcache替換成EA,並提供相關簡單調優腳本及配置文件。

更多的及更新資料請關注: http://www.linuxtone.org

十5、Nginx監控

一、 RRDTOOL+Perl腳本畫圖監控
先安裝好rrdtool ,關於rrdtool本文不做介紹,具體安裝請參照linuxtone監控版塊.

#cd /usr/local/sbnin
#wget http://blog.kovyrin.net/files/mrtg/rrd_nginx.pl.txt
#mv rrd_nginx.pl.txt rrd_nginx.pl
#chmod a+x rrd_nginx.pl
#vi rrd_nginx.pl //配置腳本文件設置好路徑

#!/usr/bin/perl
use RRDs;
use LWP::UserAgent;

# define location of rrdtool databases
my $rrd = '/data/www/wwwroot/nginx/rrd';

# define location of images
my $img = '/data/www/wwwroot/nginx/html';

# define your nginx stats URL
my $URL = "http:// 219.32.205.13/nginx_status";
…………
【注】根據本身具體的情況修改相應的路徑.

#crontab –e //加入以下

* * * * * /usr/local/sbin/rrd_nginx.pl
重啓crond後,經過配置nginx虛擬主機指到/data/www/wwwroot/nginx/html目錄,經過crond
自動執行perl腳本會生成不少圖片.

http://xxx/connections-day.png便可看到服務器狀態圖。

二、 官方Nginx-rrd 監控服務(多虛擬主機)(推薦)
網址:http://www.nginx.eu/nginx-rrd.html

此解決方案實際上是基於上述監控方案的一個改進和加強,一樣先安裝好rrdtool這個畫圖工
具和相應的perl模塊再作以下操做:

# yum install perl-HTML*
先創建好生成的庫存和圖片存放錄

#mkdir -p /data/www/wwwroot/nginx/{rrd,html}
#cd /usr/local/sbin
#wget http://www.nginx.eu/nginx-rrd/nginx-rrd-0.1.4.tgz
#tar zxvf nginx-rrd-0.1.4.tgz
#cd nginx-rrd-0.1.4
#cd etc/
#cp nginx-rrd.conf /etc
#cd etc/cron.d
#cp nginx-rrd.cron /etc/cron.d
#cd /usr/local/src/nginx-rrd-0.1.4/html
# cp index.php /data/www/wwwroot/nginx/html/
#cd /usr/local/src/nginx-rrd-0.1.4/usr/sbin
#cp * /usr/sbin/
#vi /etc/nginx-rrd.conf

#####################################################
#
# dir where rrd databases are stored

RRD_DIR="/data/www/wwwroot/nginx/rrd";

# dir where png images are presented

WWW_DIR="/data/www/wwwroot/nginx/html";

# process nice level

NICE_LEVEL="-19";

# bin dir

BIN_DIR="/usr/sbin";

# servers to test

# server_utl;server_name

SERVERS_URL="http://219.32.205.13/nginx_status;219.32.205.13
http://www.linuxtone.org/nginx_status;www.linuxtone.org"" //根據你的具體狀況作調整.

SEVERS_URL 格式 http://domain1/nginx_status;domain1

http://domain2/nginx_status;domain2

這種格式監控多虛擬主機鏈接狀態:
重點啓crond服務,仍後經過http://219.32.205.13/nginx/html/ 便可訪問。配置過程很簡單!

三、 CACTI模板監控Nginx

利用Nginx_status狀態來畫圖實現CACTI監控
nginx編譯時容許http_stub_status_module

# vi /usr/local/nginx/conf/nginx.conf

location /nginx_status {
    stub_status on;
    access_log off;
    allow 192.168.1.37;
    deny all;
}# kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
# wget http://forums.cacti.net/download.php?id=12676
# tar xvfz cacti-nginx.tar.gz
# cp cacti-nginx/get_nginx_socket_status.pl /data/cacti/scripts/
# cp cacti-nginx/get_nginx_clients_status.pl /data/cacti/scripts/
# chmod 755 /data/cacti/scripts/get_nginx*
檢測插件
# /data/cacti/scripts/get_nginx_clients_status.pl http://192.168.1.37/nginx_status

在cacti管理面板導入

cacti_graph_template_nginx_clients_stat.xml
cacti_graph_template_nginx_sockets_stat.xml
十6、常見問題與錯誤處理

一、 400 bad request錯誤的緣由和解決辦法
配置nginx.conf相關設置以下.

client_header_buffer_size 16k;
large_client_header_buffers 4 64k;
根據具體狀況調整,通常適當調整值就能夠。

二、 Nginx 502 Bad Gateway錯誤

proxy_next_upstream error timeout invalid_header http_500 http_503;
或者嘗試設置:

large_client_header_buffers 4 32k;
三、 Nginx出現的413 Request Entity Too Large錯誤

這個錯誤通常在上傳文件的時候會出現,

編輯Nginx主配置文件Nginx.conf,找到http{}段,添加

client_max_body_size 10m; //設置多大根據本身的需求做調整.
若是運行php的話這個大小client_max_body_size要和php.ini中的以下值的最大值
一致或者稍大,這樣就不會由於提交數據大小不一致出現的錯誤。

post_max_size = 10M
upload_max_filesize = 2M
四、 解決504 Gateway Time-out(nginx)

遇到這個問題是在升級discuz論壇的時候遇到的

通常看來, 這種狀況多是因爲nginx默認的fastcgi進程響應的緩衝區過小形成的,
這將致使fastcgi進程被掛起, 若是你的fastcgi服務對這個掛起處理的很差, 那麼最後就
極有可能致使504 Gateway Time-out

如今的網站, 尤爲某些論壇有大量的回覆和不少內容的, 一個頁面甚至有幾百K。

默認的fastcgi進程響應的緩衝區是8K, 咱們能夠設置大點

在nginx.conf裏, 加入:

fastcgi_buffers 8 128k
這表示設置fastcgi緩衝區爲8×128k

固然若是您在進行某一項即時的操做, 可能須要nginx的超時參數調大點,例如設置成60秒:

send_timeout 60;
只是調整了這兩個參數, 結果就是沒有再顯示那個超時, 能夠說效果不錯, 可是也
多是因爲其餘的緣由, 目前關於nginx的資料不是不少, 不少事情都須要長期的經驗
累計纔有結果, 期待您的發現哈!

五、 如何使用Nginx Proxy

朋友一臺服務器運行tomcat 爲8080端口,IP:192.168.1.2:8080,另外一臺機器
IP:192.168.1.8. 朋友想經過訪問http://192.168.1.8便可訪問tomcat服務.配置以下:

在192.168.1.8的nginx.conf上配置以下:

server {
    listen 80;
    server_name Java.linuxtone.org
    location / {
        proxy_pass http://192.168.1.2:8080;
        include /usr/local/nginx/conf/proxy.conf;
    }
}
六、 如何關閉Nginx的LOG

access_log /dev/null;
error_log /dev/null;

 

Nginx反向代理tomcat服務器 


1、Tomcat
基本配置

1.爲Tomcat提供SysV腳本
2.catalina 腳本講解
3.telnet 登陸管理Tomcat
4.配置Tomcat虛擬主機
5.Tomcat圖形管理接口

6.部署JSP網站案例

 


2、Nginx反向代理Tomcat服務器 

 

 


1.Nginx將請求反向代理到後端Tomcat
2.Nginx將圖片緩存到本地
3.Nginx將請求實現動靜分離 

 

注,實驗環境說明,操做系統:CentOS 6.4 x86_64,軟件版本:jdk-7u40、apache-tomcat-

7.0.4二、Nginx-1.4.2,博客中所用到的軟件請到這裏下載:http://yunpan.cn/QGBCLwrZnpLMS

1、Tomcat 基本配置

1.爲Tomcat提供SysV腳本

注,在上一篇博文中咱們已經演示安裝了Tomcat,這裏咱們就不在演示,不清楚的博友能夠

參考這篇博文,http://freeloda.blog.51cto.com/2033581/1299644,在上一篇博文中咱們沒有

增長,SysV腳本,在這篇博文中咱們來增長一下,下面咱們就來具體演示一下。

[root@tomcat ~]# vim /etc/init.d/tomcat
#!/bin/sh
# Tomcat init script for Linux.
#
# chkconfig: 2345 96 14
# description: The Apache Tomcat servlet/JSP Container.
CATALINA_HOME=/usr/local/tomcat #注意你的腳本路徑
export CATALINA_HOME
# export CATALINA_OPTS="-Xms128m -Xmx256m"
exec $CATALINA_HOME/bin/catalina.sh $*

下面咱們來增長執行權限,並加入服務列表設置開機自啓動,

[root@tomcat ~]# chmod +x /etc/init.d/tomcat
[root@tomcat ~]# chkconfig --add tomcat
[root@tomcat ~]# chkconfig tomcat --list

tomcat 0:關閉 1:關閉 2:啓用 3:啓用 4:啓用 5:啓用 6:關閉

下面咱們來啓動一下Tomcat並測試一下,

[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar

查看一下啓動的端口號,

[root@tomcat ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1044/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1121/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   12988/sshd
tcp    0   0 127.0.0.1:6011       0.0.0.0:*          LISTEN   13053/sshd
tcp    0   0 :::8080           :::*            LISTEN   13088/java
tcp    0   0 :::22            :::*            LISTEN   1044/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1121/master
tcp    0   0 ::1:6010          :::*            LISTEN   12988/sshd
tcp    0   0 ::1:6011          :::*            LISTEN   13053/sshd
tcp    0   0 ::ffff:127.0.0.1:8005    :::*            LISTEN   13088/java
tcp    0   0 :::8009           :::*            LISTEN   13088/java

用瀏覽器訪問一下,

 

好了,到這裏Tomcat的SysV腳本增長完成,下面咱們來講一下catalina腳本。

2.catalina 腳本講解

首先咱們來查看一下這個腳本,

[root@tomcat bin]# catalina.sh -h
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Usage: catalina.sh ( commands ... )
commands:
 debug       Start Catalina in a debugger
 debug -security  Debug Catalina with a security manager
 jpda start    Start Catalina under JPDA debugger
 run        Start Catalina in the current window
 run -security   Start in the current window with security manager
 start       Start Catalina in a separate window
 start -security  Start in a separate window with security manager
 stop       Stop Catalina, waiting up to 5 seconds for the process to end
 stop n      Stop Catalina, waiting up to n seconds for the process to end
 stop -force    Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running
 stop n -force   Stop Catalina, wait up to n seconds and then use kill -KILL if still running
 configtest    Run a basic syntax check on server.xml - check exit code for result
 version      What version of tomcat are you running?
Note: Waiting for the process to end and use of the -force option require that 

$CATALINA_PID is defined

注,從幫助上來看,這個腳本使用仍是挺簡單的。下面咱們來講幾個經常使用的選項,

catalina.sh

下面咱們就來具體演示一下,

[root@tomcat ~]# catalina.sh configtest
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
九月 21, 2013 11:08:26 下午 org.apache.catalina.core.AprLifecycleListener init
信息: The APR based Apache Tomcat Native library which allows optimal performance in

production environments was not found on the java.library.path: 

/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
九月 21, 2013 11:08:27 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-bio-8080"]
九月 21, 2013 11:08:27 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["ajp-bio-8009"]
九月 21, 2013 11:08:27 下午 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 1269 ms

注,使用configtest選項時,得關閉Tomcat,否則會報錯。

啓動Tomcat,

[root@tomcat ~]# catalina.sh start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar

關閉Tomcat,

[root@tomcat ~]# catalina.sh stop
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar

查看Tomcat版本,

[root@tomcat ~]# catalina.sh version
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.7.0_40
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.42
Server built:  Jul 2 2013 08:57:41
Server number: 7.0.42.0
OS Name:    Linux
OS Version:   2.6.32-358.el6.x86_64
Architecture:  amd64
JVM Version:  1.7.0_40-b43
JVM Vendor:   Oracle Corporation

好了,catalina腳本,咱們就說到這裏了,下面咱們來講一下telnet管理Tomcat。

3.telnet 登陸管理Tomcat

注,在說telnet管理Tomcat以前,咱們得先看一下默認的配置文件,這裏面定義了默認的管理

端口,

[root@tomcat ~]# vim /usr/local/tomcat/conf/server.xml
<Server port="8005" shutdown="SHUTDOWN">

說明,定義了一個管理端口爲8005,咱們能夠用telnet直接登陸進本機的8005端口,來執行

SHUTDOWN命令,來關閉Tomcat實例。下面咱們來具體演示一下,

先安裝telnet客戶端,

[root@tomcat ~]# yum install -y telnet

下面咱們一測試並查看,

[root@tomcat ~]# telnet localhost 8005
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
SHUTDOWN #輸入SHOWDOWN就能夠直接關閉Tomcat服務。
Connection closed by foreign host.
[root@tomcat ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1044/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1121/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   12988/sshd
tcp    0   0 127.0.0.1:6011       0.0.0.0:*          LISTEN   13053/sshd
tcp    0   0 :::22            :::*            LISTEN   1044/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1121/master
tcp    0   0 ::1:6010          :::*            LISTEN   12988/sshd
tcp    0   0 ::1:6011          :::*            LISTEN   13053/sshd

注,你們能夠看到Tomcat服務器已經關閉。好了,telnet管理咱們就說到這裏,下面咱們來講

一下,Tomcat虛擬主機的配置。

4.配置Tomcat虛擬主機

注,在說Tomcat虛擬主機以前,我們來詳細的看看默認的配置文件,雖然在上一篇博客中全

部有講解,在這篇博客中我仍是再和你們簡單說一下,下面是默認配置文件。你們能夠看到,

絕大部分的配置文件是註釋,包含在<!-- -->、全是註釋。下面咱們就來具體的看看,註釋我

們就不說了,說具體的定義的內容

[root@tomcat ~]# cat /usr/local/tomcat/conf/server.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<!-- Note: A "Server" is not itself a "Container", so you may not
   define subcomponents such as "Valves" at this level.
   Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN"> #你們能夠看到,這裏是咱們剛纔講解的,

定義一個管理接口
 <!-- Security listener. Documentation at /docs/config/listeners.html
 <Listener className="org.apache.catalina.security.SecurityListener" />
 -->
 <!--APR library loader. Documentation at /docs/apr.html -->
 <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
 <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-

howto.html -->
 <Listener className="org.apache.catalina.core.JasperListener" />
 <!-- Prevent memory leaks due to use of particular java/javax APIs-->
 <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
 <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
 <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
 <!-- Global JNDI resources
    Documentation at /docs/jndi-resources-howto.html
 -->
 <GlobalNamingResources>
  <!-- Editable user database that can also be used by
     UserDatabaseRealm to authenticate users
  -->
  <Resource name="UserDatabase" auth="Container"
       type="org.apache.catalina.UserDatabase"
       description="User database that can be updated and saved"
       factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
       pathname="conf/tomcat-users.xml" />
 </GlobalNamingResources>
 <!-- A "Service" is a collection of one or more "Connectors" that share
    a single "Container" Note: A "Service" is not itself a "Container",
    so you may not define subcomponents such as "Valves" at this level.
    Documentation at /docs/config/service.html
  -->
 <Service name="Catalina"> #定義一個Service命令爲Catalina
  <!--The connectors can use a shared executor, you can define one or more named thread

pools-->
  <!--
  <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
    maxThreads="150" minSpareThreads="4"/>
  -->
  <!-- A "Connector" represents an endpoint by which requests are received
     and responses are returned. Documentation at :
     Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
     Java AJP Connector: /docs/config/ajp.html
     APR (HTTP/AJP) Connector: /docs/apr.html
     Define a non-SSL HTTP/1.1 Connector on port 8080
  -->
  <Connector port="8080" protocol="HTTP/1.1"
        connectionTimeout="20000"
        redirectPort="8443" /> #這裏定義了一個鏈接器,協議爲http,端口爲8080,最大鏈接

超時爲20s,這裏還定義了一個SSL的重定向端口8443。咱們能夠根據須要進行修改。通常我

們都用80端口與443端口。
  <!-- A "Connector" using the shared thread pool-->
  <!--
  <Connector executor="tomcatThreadPool"
        port="8080" protocol="HTTP/1.1"
        connectionTimeout="20000"
        redirectPort="8443" />
  -->
  <!-- Define a SSL HTTP/1.1 Connector on port 8443
     This connector uses the JSSE configuration, when using APR, the
     connector should be using the OpenSSL style configuration
     described in the APR documentation -->
  <!--
  <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
        maxThreads="150" scheme="https" secure="true"
        clientAuth="false" sslProtocol="TLS" /> #這裏定義了一個SSL的案例,主要定義相關密

鑰與證書。
  -->
  <!-- Define an AJP 1.3 Connector on port 8009 -->
  <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /> #這裏定義了一個支持

AJP協議的鏈接器。
  <!-- An Engine represents the entry point (within Catalina) that processes
     every request. The Engine implementation for Tomcat stand alone
     analyzes the HTTP headers included with the request, and passes them
     on to the appropriate Host (virtual host).
     Documentation at /docs/config/engine.html -->
  <!-- You should set jvmRoute to support load-balancing via AJP ie :
  <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
  -->
  <Engine name="Catalina" defaultHost="localhost"> #這裏定義了一個名爲Catalina的引擎,

並定義了一個默認主機爲localhost。
   <!--For clustering, please take a look at documentation at:
     /docs/cluster-howto.html (simple how to)
     /docs/config/cluster.html (reference documentation) -->
   <!--
   <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
   -->
   <!-- Use the LockOutRealm to prevent attempts to guess user passwords
      via a brute-force attack -->
   <Realm className="org.apache.catalina.realm.LockOutRealm">
    <!-- This Realm uses the UserDatabase configured in the global JNDI
       resources under the key "UserDatabase". Any edits
       that are performed against this UserDatabase are immediately
       available for use by the Realm. -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
        resourceName="UserDatabase"/>
   </Realm>
   <Host name="localhost" appBase="webapps"
      unpackWARs="true" autoDeploy="true"> #這裏就是定義的虛擬主機。
    <!-- SingleSignOn valve, share authentication between web applications
       Documentation at: /docs/config/valve.html -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->
    <!-- Access log processes all example.
       Documentation at: /docs/config/valve.html
       Note: The pattern used is equivalent to using pattern="common" -->
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
        prefix="localhost_access_log." suffix=".txt"
        pattern="%h %l %u %t &quot;%r&quot; %s %b" /> #這裏定義了一個日誌相關的屬

性。
   </Host>
  </Engine>
 </Service>
</Server>

好了,在這裏咱們又簡單的說明一下,配置文件下面咱們就來具體演示一下怎麼配置虛擬主機

首先,咱們來修改一下配置文件,

[root@tomcat conf]# vim server.xml

#增長下面幾行

<Host name="www.test.com" appBase="/web/webapp"
   unpackWARs="true" autoDeploy="true">
     <Context path="/" docBase="/web/webapp" reloadable="true"/>
</Host>

接下來咱們來建立文檔目錄與測試頁面,

[root@tomcat ~]# mkdir -pv /web/webapp
[root@tomcat ~]# cd /web/webapp
[root@tomcat webapp]# vim index.jsp
<%@ page language="java" %>
<%@ page import="java.util.*" %>
<html>
 <head>
  <title>JSP test page.</title>
 </head>
 <body>
  <% out.println("Welcome to test. Site, http://www.test.com"); %>
 </body>
</html>

如今咱們來測試一下咱們修改的配置文件,

[root@tomcat ~]# service tomcat stop
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
^[[A[root@tomcat service tomcat configtest
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Sep 22, 2013 2:15:47 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in

production environments was not found on the java.library.path: 

/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Sep 22, 2013 2:15:47 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-80"]
Sep 22, 2013 2:15:47 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 22, 2013 2:15:47 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1294 ms

注,你們能夠看到,咱們這裏沒有報錯,說明配置都是正確的,若配置有錯誤,會在最後一行

提醒你。

再下面咱們來啓動Tomcat並測試一下,

[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp Active Internet connections (only servers) Proto Recv-Q

Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:*

LISTEN 1044/sshd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1121/master tcp 0 0 

127.0.0.1:6010 0.0.0.0:* LISTEN 13368/sshd tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN

13387/sshd tcp 0 0 127.0.0.1:6012 0.0.0.0:* LISTEN 13407/sshd tcp 0 0 :::80 :::* LISTEN

13557/java tcp 0 0 :::22 :::* LISTEN 1044/sshd tcp 0 0 ::1:25 :::* LISTEN 1121/master tcp

0 0 ::1:6010 :::* LISTEN 13368/sshd tcp 0 0 ::1:6011 :::* LISTEN 13387/sshd tcp 0 0

::1:6012 :::* LISTEN 13407/sshd tcp 0 0 :::8009 :::* LISTEN 13557/java 
注,還有一點得說明一下,我這裏爲了方便測試,將默認端口8080修改成了80端口。下面是

測試效果,

 

爲了幫助你們理解,咱們這裏再次講解一下,Host組件與Context組件以及相關屬性。

Host組件:

位於Engine容器中用於接收請求並進行相應處理的主機或虛擬主機,如前面咱們自定義的內容

<Host name="www.server110.com" appBase="/web/webapp"
   unpackWARs="true" autoDeploy="true">
     <Context path="/" docBase="/web/webapp" reloadable="true"/>
</Host>

經常使用屬性說明:

name:定義虛擬主機的域名

appBase:此Host的webapps目錄,即存放非歸檔的web應用程序的目錄或歸檔後的WAR文件

的目錄路徑;可使用基於$CATALINA_HOME的相對路徑;

autoDeploy:在Tomcat處於運行狀態時放置於appBase目錄中的應用程序文件是否自動進行

deploy;默認爲true;

unpackWars:在啓用此webapps時是否對WAR格式的歸檔文件先進行展開;默認爲true;

主機別名定義:

若是一個主機有兩個或兩個以上的主機名,額外的名稱都可以以別名的形式進行定義,以下:

<Host name="www.test.com" appBase="webapps" unpackWARs="true">
 <Alias>web.test.com</Alias>
</Host>
Context組件:
Context在某些意義上相似於apache中的路徑別名,一個Context定義用於標識tomcat實例中的

一個Web應用程序。以下面的定義:
  <!-- Tomcat Root Context -->
  <Context path="" docBase="/web/webapps"/>
  <!-- buzzin webapp -->
  <Context path="/bbs"
   docBase="/web/threads/bbs"
   reloadable="true">
  </Context>
  <!-- chat server -->
   <Context path="/chat" docBase="/web/chat"/>
  <!-- darian web -->
  <Context path="/darian" docBase="darian"/>

在Tomcat中,每個context定義也可使用一個單獨的XML文件進行,其文件的目錄爲

$CATALINA_HOME/conf/<engine name>/<host name>。能夠用於Context中的XML元素有

Loader,Manager,Realm,Resources和WatchedResource。

經常使用的屬性定義有:

docBase:相應的Web應用程序的存放位置;也可使用相對路徑,起始路徑爲此Context所屬

Host中appBase定義的路徑;切記,docBase的路徑名不能與相應的Host中appBase中定義的路

徑名有包含關係,好比,若是appBase爲deploy,而docBase毫不能爲deploy-bbs類的名字;

path:相對於Web服務器根路徑而言的URI;若是爲空「」,則表示爲此webapp的根路徑;若是

context定義在一個單獨的xml文件中,此屬性不須要定義;

reloadable:是否容許從新加載此context相關的Web應用程序的類;默認爲false;

爲了便於你們理解,咱們這裏再定義一個Context並測試一下,

咱們先來修改一下配置文件

[root@tomcat conf]# vim server.xml
<Host name="www.test.com" appBase="/web/webapp"
    unpackWARs="true" autoDeploy="true">
      <Context path="/" docBase="/web/webapp" reloadable="true"/>
      <Context path="/test" docBase="/web/test" reloadable="true"/> #增長這一行
 </Host>

下面來增長目錄文檔與測試文件,

[root@tomcat webapp]# mkdir /web/test
[root@tomcat webapp]# cd /web/test
[root@tomcat test]# vim index.jsp
<%@ page language="java" %>
<html>
 <head><title>TomcatA</title></head>
 <body>
  <h1><font color="red">TomcatA </h1>
  <table align="centre" >
   <tr>
    <td>Session ID</td>
  <% session.setAttribute("abc","abc"); %>
    <td><%= session.getId() %></td>
   </tr>
   <tr>
    <td>Created on</td>
    <td><%= session.getCreationTime() %></td>
   </tr>
  </table>
 </body>
</html>

測試一下配置文件是否有錯並啓動Tomcat,

[root@tomcat ~]# service tomcat configtest Using CATALINA_BASE: /usr/local/tomcat Using

CATALINA_HOME: /usr/local/tomcat Using CATALINA_TMPDIR: /usr/local/tomcat/temp Using

JRE_HOME: /usr Using CLASSPATH: 

/usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar Sep 22, 2013 2:40:57

AM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat

Native library which allows optimal performance in production environments was not found

on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib Sep 22,

2013 2:40:58 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler

["http-bio-80"] Sep 22, 2013 2:40:58 AM org.apache.coyote.AbstractProtocol init INFO:

Initializing ProtocolHandler ["ajp-bio-8009"] Sep 22, 2013 2:40:58 AM 

org.apache.catalina.startup.Catalina load INFO: Initialization processed in 1352 ms
[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp Active Internet connections (only servers) Proto Recv-Q

Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:*

LISTEN 1044/sshd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1121/master tcp 0 0 

127.0.0.1:6010 0.0.0.0:* LISTEN 13587/sshd tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN

13387/sshd tcp 0 0 127.0.0.1:6012 0.0.0.0:* LISTEN 13407/sshd tcp 0 0 :::80 :::* LISTEN

13945/java tcp 0 0 :::22 :::* LISTEN 1044/sshd tcp 0 0 ::1:25 :::* LISTEN 1121/master tcp

0 0 ::1:6010 :::* LISTEN 13587/sshd tcp 0 0 ::1:6011 :::* LISTEN 13387/sshd tcp 0 0

::1:6012 :::* LISTEN 13407/sshd tcp 0 0 ::ffff:127.0.0.1:8005 :::* LISTEN 13945/java tcp 0

0 :::8009 :::* LISTEN 13945/java 
下面咱們就用瀏覽器測試一下,

 

好了,到這裏咱們的Tomcat虛擬主機的講解就到這裏了,下面咱們來講一下Tomcat圖形管理

接口。

5.Tomcat圖形管理接口

咱們先來看一下默認的圖形配置界面,

 

注,你們注意看右上角,我用紅色方框標記出來的,你們能夠看有三個按鈕,分別爲

Server Status 主要用來查看服務器的狀態

Manager App 主要用來管理應用程序的部署及監控

Host Manager 主要用來管理虛擬主機

下面咱們就來具休的配置一下,你們能夠看到,你點擊任何一個按鈕都要輸入用戶名和密碼的

,在咱們配置以前咱們先來講一下,Tomcat的Manager功能,

Manager的四個管理角色:

manager-gui - allows access to the HTML GUI and the status pages

manager-script - allows access to the text interface and the status pages

manager-jmx - allows access to the JMX proxy and the status pages

manager-status - allows access to the status pages only

注,這裏我說一下,上面的英文比較簡單我就不在裏翻譯了,你們本身看一下。

下面咱們就來啓用manager功能,修改tomcat-user.xml文件,添加以下行:

<role rolename="manager-gui"/>
<role rolename="admin-gui"/>
<user username="tomcat" password="tomcat" roles="manager-gui,admin-gui"/>

簡單解釋一下,Tomcat有內置的角色,咱們這裏增長了兩個角色一個爲manager-gui,另外一個

爲admin-gui,用戶名和密碼都爲tomcat。

 

注,增長的內容必定要在<tomcat-users></tomcat-users>之間。否則,不會生效。好了,下

面咱們一來測試一下配置文件,並從新啓動一下Tomcat

[root@tomcat ~]# service tomcat configtest Using CATALINA_BASE: /usr/local/tomcat Using

CATALINA_HOME: /usr/local/tomcat Using CATALINA_TMPDIR: /usr/local/tomcat/temp Using

JRE_HOME: /usr Using CLASSPATH: 

/usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar Sep 22, 2013 3:08:44

AM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat

Native library which allows optimal performance in production environments was not found

on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib Sep 22,

2013 3:08:44 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler

["http-bio-80"] Sep 22, 2013 3:08:44 AM org.apache.coyote.AbstractProtocol init INFO:

Initializing ProtocolHandler ["ajp-bio-8009"] Sep 22, 2013 3:08:44 AM 

org.apache.catalina.startup.Catalina load INFO: Initialization processed in 1213 ms
[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp Active Internet connections (only servers) Proto Recv-Q

Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:*

LISTEN 1044/sshd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1121/master tcp 0 0 

127.0.0.1:6010 0.0.0.0:* LISTEN 13587/sshd tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN

13387/sshd tcp 0 0 127.0.0.1:6012 0.0.0.0:* LISTEN 13407/sshd tcp 0 0 :::80 :::* LISTEN

14197/java tcp 0 0 :::22 :::* LISTEN 1044/sshd tcp 0 0 ::1:25 :::* LISTEN 1121/master tcp

0 0 ::1:6010 :::* LISTEN 13587/sshd tcp 0 0 ::1:6011 :::* LISTEN 13387/sshd tcp 0 0

::1:6012 :::* LISTEN 13407/sshd tcp 0 0 ::ffff:127.0.0.1:8005 :::* LISTEN 14197/java tcp 0

0 :::8009 :::* LISTEN 14197/java 
好了,下面咱們用瀏覽器查看一下,

注,點擊Server Status按鈕,讓你輸入用戶名和密碼。我這裏所有設置是tomcat。

 

而後,會出現如下界面。顯示所有服務器運行狀態!你們能夠仔細的看一下,我就不帶着你們

看了。

 

下面是應用程序部署管理界面,

 

下面是虛擬主機管理頁面,

 

注,咱們通常在生產環境中用的最可能是應用程序部署界面,能夠進行熱佈署應用程序,很方便

,你們能夠嘗試一下。好了,圖形管理界面咱們就說到這裏了,下面咱們來講一下,Tomcat

的一個小案例。咱們說了那麼多,有朋友就會說了,怎麼一個案例也沒有呢?下面咱們就來布

署一個社交網站的案例JavaCenter Home。

6.部署JSP網站案例

首頁,咱們來修改一下配置文件,

[root@tomcat conf]# vim server.xml
<Host name="www.test.com" appBase="/web"
   unpackWARs="true" autoDeploy="true">
 <Context path="/" docBase="webapp" reloadable="true"/>
</Host>

注,增長一下虛擬主機,文件目錄爲/web/webapp。

下面咱們來解壓一下咱們下載好的JavaCenter Home網站程序,

[root@tomcat src]# tar xf JavaCenter_Home_2.0_GBK.tar.bz2

接下來將解壓好的JavaCenter Home程序移動到/web/webapp下,

[root@tomcat src]# cd JavaCenter_Home_2.0_GBK
[root@tomcat JavaCenter_Home_2.0_GBK]# mv * /web/webapp/

下面咱們來測試一下配置文件並啓動Tomcat服務,

[root@tomcat ~]# service tomcat configtest
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.6.0_21
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Sep 23, 2013 5:31:18 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in

production environments was not found on the java.library.path: 

/usr/java/jdk1.6.0_21/jre/lib/amd64/server:/usr/java/jdk1.6.0_21/jre/lib/amd64:/usr/java/jdk

1.6.0_21/jre/../lib/amd64:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Sep 23, 2013 5:31:20 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-80"]
Sep 23, 2013 5:31:20 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 23, 2013 5:31:20 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2493 ms
[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.6.0_21
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1026/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1256/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   1339/sshd
tcp    0   0 0.0.0.0:3306        0.0.0.0:*          LISTEN   1165/mysqld
tcp    0   0 :::80            :::*            LISTEN   1499/java
tcp    0   0 :::22            :::*            LISTEN   1026/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1256/master
tcp    0   0 ::1:6010          :::*            LISTEN   1339/sshd
tcp    0   0 :::8009           :::*            LISTEN   1499/java

下面咱們用瀏覽器訪問一下,http://www.test.com(注,要想用域名訪問,必須配置本機有

hosts文件,Windows7hosts文件目錄,C:\Windows\System32\drivers\etc\hosts)

 

注,上面的錯誤說明咱們鏈接MySQL數據庫失敗。由於咱們這裏尚未安裝與配置嘛。下面我

們趕快來配置一下,

先安裝數據庫,咱們這裏就用yum安裝一下,

[root@tomcat ~]# yum install -y mysql-server

下面來啓動並配置mysql,

[root@tomcat ~]# service mysqld start
Starting mysqld:                      [ OK ]
[root@tomcat ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.1.69 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>

好了,到這裏咱們mysql就安裝完成了,下面咱們來看一下咱們的程序目錄,

[root@tomcat ~]# cd /web/webapp/
[root@tomcat webapp]# ls
admin    avatar.jsp     data     help.jsp  js.jsp    rss.jsp  userapp.jsp
admincp.jsp config.properties do.jsp    image    link.jsp   source   WEB-INF
api     contact.jsp    editor.jsp  index.jsp  magic.jsp  space.jsp xmlrpc.jsp
app.jsp   cp.jsp       errors    install   META-INF   template
attachment  crossdomain.xml  favicon.ico invite.jsp network.jsp theme

你們能夠看到裏面有個install的目錄,下面咱們用瀏覽器訪問一下,

http://www.test.com/install,會跳出一個安裝界面,以下圖

 

從圖中,咱們能夠看出,因此環境配置完成,都符合要求。下面咱們點擊「接受受權協議,開

始安裝JavaCenter Home」,會跳出下一界面,以下圖

 

從圖中,咱們能夠看出得輸入,數據庫名稱、數據庫用戶名、數據庫密碼。下面咱們就來增長

一下,

[root@tomcat ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 5.1.69 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database jcenter;
Query OK, 1 row affected (0.00 sec)
mysql> grant all privileges on jcenter.* to jcenter@'localhost' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
mysql> grant all privileges on jcenter.* to jcenter@'127.0.0.1' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

上面建立一個jcenter數據庫,受權訪問一個jcenter用戶,密碼爲123456。下面咱們繼續配置

 

咱們輸入剛纔設置的數據庫用戶名、數據庫密碼、數據庫名稱。點擊「設置完畢,檢測個人數

據庫配置」,圖顯示的3和4會看自動進行安裝,咱們只等一會便可。安裝完成的效果以下圖,

 

下面咱們開通一個管理員空間,用戶名和密碼都爲admin,以下圖

 

點擊「開通管理員空間」,會跳出另外一個界面,以下圖

 

咱們點擊「進入空間首頁」,效果以下圖

 

好了,到這裏咱們的JavaCenter Home就所有配置完成了,咱們第一階段的基本配置就這裏全

部完成,下面咱們主要講解Nginx反向代理Tomcat服務器。

2、Nginx反向代理Tomcat服務器

0.測試環境準備階段

下面先看一下實驗拓撲,

 

接着來同步各節點時間,

[root@tomcat ~]# ntpdate 202.120.2.101
[root@nginx ~]# ntpdate 202.120.2.101

下面咱們來安裝nginx服務器,首先來解決nginx的依賴關係,

[root@nginx ~]# yum groupinstall -y "Development Tools" "Server Platform Deveopment"
[root@nginx ~]# yum install -y openssl-devel pcre-devel

下面咱們來新建nginx用戶,

[root@nginx ~]# groupadd -r -g 108 nginx
[root@nginx ~]# useradd -r -g 108 -u 108 nginx
[root@nginx ~]# id nginx
uid=108(nginx) gid=108(nginx) 組=108(nginx)

接着咱們來開始編譯和安裝,

[root@nginx src]# tar xf nginx-1.4.2.tar.gz
[root@nginx src]# cd nginx-1.4.2
[root@nginx nginx-1.4.2]# ls
auto CHANGES CHANGES.ru conf configure contrib html LICENSE man README src
[root@nginx nginx-1.4.2]# ./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
[root@nginx nginx-1.4.2]# make && make install

說明:

Nginx可使用Tmalloc(快速、多線程的malloc庫及優秀性能分析工具)來加速內存分配,使用

此功能須要事先安裝gperftools,然後在編譯nginx添加--with-google_perftools_module選項即

可。

若是想使用nginx的perl模塊,能夠經過爲configure腳本添加--with-http_perl_module選項來實

現,但目前此模塊仍處於實驗性使用階段,可能會在運行中出現意外,所以,其實現方式這裏

再也不介紹。若是想使用基於nginx的cgi功能,也能夠基於FCGI來實現,具體實現方法請參照網

上的文檔。

下面咱們爲nginx提供SysV init腳本,

[root@nginx ~]# cat /etc/init.d/nginx
#!/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/nginx
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

然後爲此腳本賦予執行權限,

[root@nginx ~]# chmod +x /etc/init.d/nginx

添加至服務管理列表,並讓其開機自動啓動,

[root@nginx ~]# chkconfig --add nginx
[root@nginx ~]# chkconfig nginx on

然後就能夠啓動服務並測試了,

[root@nginx ~]# service nginx start
正在啓動 nginx:                      [肯定]
[root@nginx ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:80         0.0.0.0:*          LISTEN   14006/nginx
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1029/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1105/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   1345/sshd
tcp    0   0 :::22            :::*            LISTEN   1029/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1105/master
tcp    0   0 ::1:6010          :::*            LISTEN   1345/sshd

下面是測試結果,

 

好了,到這裏咱們準備工做就所有完成了,下面們來簡單的配置一下Nginx反向代理Tomcat服

務器。

1.Nginx將請求反向代理到後端Tomcat

首先,咱們來修改一下nginx的配置文件,

[root@nginx ~]# cd /etc/nginx/
[root@nginx nginx]# cp nginx.conf nginx.conf.bak
[root@nginx nginx]# vim nginx.conf
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid    logs/nginx.pid;
events {
  worker_connections 1024;
}
http {
  include    mime.types;
  default_type application/octet-stream;
  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  #         '$status $body_bytes_sent "$http_referer" '
  #         '"$http_user_agent" "$http_x_forwarded_for"';
  #access_log logs/access.log main;
  sendfile    on;
  #tcp_nopush   on;
  #keepalive_timeout 0;
  keepalive_timeout 65;
  #gzip on;
  server {
    listen    80;
    server_name localhost;
    #charset koi8-r;
    #access_log logs/host.access.log main;
    location / {
      #root  html;
      #index index.html index.htm;
      proxy_pass http://192.168.18.201/; #註釋默認兩行,新增一行。
    }
    #error_page 404       /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page  500 502 503 504 /50x.html;
    location = /50x.html {
      root  html;
    }
  }
}

從新加載一下配置文件,

[root@nginx ~]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
從新載入 nginx:                      [肯定]

下面進行測試一下,(注,首先你得保證你的tomcat服務器能正常訪問,下面咱們先來訪問一

下tomcat服務器,以下圖)

 

你們能夠看到咱們的tomcat服務器能夠正常訪問,下面咱們來看測試一下nginx可不能夠進行

反向代理。(注,還有問題,這裏爲了方便測試咱們先將tomcat的默認主機設置爲

www.test.com

[root@tomcat ~]# vim /usr/local/tomcat/conf/server.xml
  <Engine name="Catalina" defaultHost="www.test.com">

從新啓動一下tomcat並測試,

[root@tomcat ~]# service tomcat stop
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.6.0_21
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# service tomcat start
Using CATALINA_BASE:  /usr/local/tomcat
Using CATALINA_HOME:  /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:    /usr/java/jdk1.6.0_21
Using CLASSPATH:    /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
[root@tomcat ~]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address        Foreign Address       State    PID/Program name
tcp    0   0 0.0.0.0:22         0.0.0.0:*          LISTEN   1026/sshd
tcp    0   0 127.0.0.1:25        0.0.0.0:*          LISTEN   1256/master
tcp    0   0 127.0.0.1:6010       0.0.0.0:*          LISTEN   1339/sshd
tcp    0   0 127.0.0.1:6011       0.0.0.0:*          LISTEN   2744/sshd
tcp    0   0 0.0.0.0:3306        0.0.0.0:*          LISTEN   2382/mysqld
tcp    0   0 :::80            :::*            LISTEN   3299/java
tcp    0   0 :::22            :::*            LISTEN   1026/sshd
tcp    0   0 ::1:25           :::*            LISTEN   1256/master
tcp    0   0 ::1:6010          :::*            LISTEN   1339/sshd
tcp    0   0 ::1:6011          :::*            LISTEN   2744/sshd
tcp    0   0 :::8009           :::*            LISTEN   3299/java

下面咱們來訪問測試一下tomcat服務器,

 

下面咱們來測試看nginx是否能代理tomcat服務器,

 

好了,你們能夠看到咱們成功設置了nginx反向代理tomcat服務器。好了,你們能夠看到,我

們網站上有不少的圖片,每次訪問都要去後端的tomcat服務器上去取,很消耗服務器資源。我

們下面將設置在nginx服務器上緩存圖片。

2.Nginx將圖片緩存到本地

一樣的,咱們先來修改配置文件,

[root@nginx nginx]# cat nginx.conf
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid    logs/nginx.pid;
events {
  worker_connections 1024;
}
http {
  include    mime.types;
  default_type application/octet-stream;
  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  #         '$status $body_bytes_sent "$http_referer" '
  #         '"$http_user_agent" "$http_x_forwarded_for"';
  #access_log logs/access.log main;
  sendfile    on;
  #tcp_nopush   on;
  #keepalive_timeout 0;
  keepalive_timeout 65;
  #gzip on;
  proxy_cache_path /nginx/cache levels=1:2 keys_zone=first:10m inactive=24h 

max_size=1G; #新建緩存路徑與相關屬性
  upstream backend { #創建後端tomcat服務器
  server 192.168.18.201 weight=1;
  }
  server {
    listen    80;
    server_name localhost;
    #charset koi8-r;
    #access_log logs/host.access.log main;
    location / {
      #root  html;
      #index index.html index.htm;
      #proxy_pass http://192.168.18.201/; #註釋原來的代理設置
      proxy_pass http://backend/; #啓動後端服務器
    }
  location ~* "\.(jpg|jpeg|png|gif|html|css|js)$" { #緩存圖片與靜態內容
    proxy_pass http://backend;
    proxy_cache first;
    proxy_cache_valid 200 24h; #200狀態緩存24小時
    proxy_cache_valid 302 10m; #302狀態緩存10分鐘
    add_header X-Cache-Status $upstream_cache_status; #在http頭部增長一個字段顯示是否

命令緩存
  }
    #error_page 404       /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page  500 502 503 504 /50x.html;
    location = /50x.html {
      root  html;
    }
  }
}

下面咱們來新建緩存目錄,

[root@nginx ~]# mkdir -pv /nginx/cache
mkdir: 已建立目錄 "/nginx"
mkdir: 已建立目錄 "/nginx/cache"

測試一下配置文件是否有錯,

[root@nginx ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

從新加載配置文件,

[root@nginx ~]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
從新載入 nginx:                      [肯定]

那麼下面咱們就來測試一下,

 

你們能夠看到咱們訪問的全部的靜態內容都是命中的,X-Cache-Status: HIT,下面們來看一下

緩存的目錄,

[root@nginx ~]# cd /nginx/cache/
[root@nginx cache]# ls
0 1 2 3 4 5 6 7 8 9 b c d e

你們能夠看到,緩存目錄當中有咱們緩存的內容,好了到這裏咱們的nginx緩存服務就配置完

成了,下面咱們看一下如何實現動靜分離。

3.Nginx將請求實現動靜分離

首先,咱們來講一下咱們要實現的效果,上面咱們已經將靜態內容緩存在nginx服務器上,我

們想讓用戶請求的靜態內容到nginx去取,動態內容到tomcat服務器上去取,這就能實現動靜

分享效果。一樣的首先咱們來修改配置文件,

[root@nginx nginx]# cat nginx.conf
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid    logs/nginx.pid;
events {
  worker_connections 1024;
}
http {
  include    mime.types;
  default_type application/octet-stream;
  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  #         '$status $body_bytes_sent "$http_referer" '
  #         '"$http_user_agent" "$http_x_forwarded_for"';
  #access_log logs/access.log main;
  sendfile    on;
  #tcp_nopush   on;
  #keepalive_timeout 0;
  keepalive_timeout 65;
  #gzip on;
  proxy_cache_path /nginx/cache levels=1:2 keys_zone=first:10m inactive=24h 

max_size=1G;
  upstream backend {
  server 192.168.18.201 weight=1;
  }
  server {
    listen    80;
    server_name localhost;
    #charset koi8-r;
    #access_log logs/host.access.log main;
  index index.jsp index.html;
    location ~* "\.(jsp|do)$" { #當請求的是jsp或do文件時直接到tomcat上去取
      #root  html;
      #index index.html index.htm;
      #proxy_pass http://192.168.18.201/;
      #proxy_pass http://backend/;
      proxy_pass http://backend;
    }
  location = / {
    root html;
    rewrite ^/ http://192.168.18.201/index.jsp last;
  }
  location ~* "\.(jpg|jpeg|png|gif|html|css|js)$" {
    proxy_pass http://backend;
    proxy_cache first;
    proxy_cache_valid 200 24h;
    proxy_cache_valid 302 10m;
    add_header X-Cache-Status $upstream_cache_status;
  }
    #error_page 404       /404.html;
    # redirect server error pages to the static page /50x.html
    #
    error_page  500 502 503 504 /50x.html;
    location = /50x.html {
      root  html;
    }
  }
}

下面咱們來檢查一下配置文件是否有誤,

[root@nginx ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

從新加載一下配置文件,

[root@nginx ~]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
從新載入 nginx:                      [肯定]

下面咱們來訪問測試一下,

 

你們能夠看到咱們的靜態內容來自緩存,動態內容所有代理到後端的tomcat服務器上了,說明

咱們動態分離配置完成,好了到這裏咱們的tomcat的基本配置與nginx反向代理tomcat的配置

就所有完成了,



Nginx502 bad gateway, 504 Gateway Time-out的徹解決方法 


VPS是256M的內存,CPU是四核心的,因此更多的我會在意內存。而在我調試服務器的時候通

常會遇到Nginx502 bad gateway和504 Gateway Time-out的錯誤。分析nginx.conf我發現

server和fastcgi的buffers過多,致使fastcgi請求的數量過大,php-fpm沒法及時處理而出錯。

循此思路咱們能夠再整體buffers不變的狀況下減小請求數量,具體的ningx.conf改動細節以下


                server_names_hash_bucket_size 128;
                client_header_buffer_size 32k;
                large_client_header_buffers 1 128k;# 4 32k
                client_max_body_size 8m;

                sendfile on;
                tcp_nopush     on;

                keepalive_timeout 60;

                tcp_nodelay on;

                fastcgi_connect_timeout 300;
                fastcgi_send_timeout 300;
                fastcgi_read_timeout 300;
                fastcgi_buffer_size 128k;
                fastcgi_buffers 2 256k;#8 128
                fastcgi_busy_buffers_size 256k;
                fastcgi_temp_file_write_size 256k;
                fastcgi_intercept_errors on;

                gzip on;
                gzip_min_length  1k;
                gzip_buffers     1 64k; #4 16
                gzip_http_version 1.0;
                gzip_comp_level 2;
                gzip_types       text/plain application/x-javascript text/css application/xml;
                gzip_vary on;

另外,php-fpm的默認靜態處理方式會使得php-cgi的進程長期佔用內存而沒法釋放,這也是導

致nginx出錯的緣由之一,所以能夠將php-fpm的處理方式改爲apache模式。
        <value name=」style」>apache-like</value>

從更改完畢到如今的測試代表上述方式的效果仍是很明顯的,並無發現一次Nginx502 bad 

gateway或504 Gateway Time-out錯誤。固然,若是你的VPS或者服務器的性能足夠好能夠根

據具體狀況沒必要作無謂的改動。

通常看來, 這種狀況多是因爲nginx默認的fastcgi進程響應的緩衝區過小形成的, 這將致使

fastcgi進程被掛起, 若是你的fastcgi服務對這個掛起處理的很差, 那麼最後就極有可能致使504 

Gateway Time-out
如今的網站, 尤爲某些論壇有大量的回覆和不少內容的, 一個頁面甚至有幾百K
默認的fastcgi進程響應的緩衝區是8K, 咱們能夠設置大點
在nginx.conf裏, 加入:


fastcgi_buffers 8 128k 

這表示設置fastcgi緩衝區爲8×128k
固然若是您在進行某一項即時的操做, 可能須要nginx的超時參數調大點, 例如設置成60秒:

send_timeout 60;

我只是調整了這兩個參數, 結果就是沒有再顯示那個超時, 能夠說效果不錯, 可是也多是因爲

其餘的緣由, 目前關於nginx的資料不是不少, 不少事情都須要長期的經驗累計纔有結果, 期待您

的發現哈!

 

 

 

Nginx 502 Bad Gateway的含義是請求的PHP-CGI已經執行,可是因爲某種緣由(通常是讀取

資源的問題)沒有執行完畢而致使PHP-CGI進程終止。
Nginx 504 Gateway Time-out的含義是所請求的網關沒有請求到,簡單來講就是沒有請求到可

以執行的PHP-CGI。

解決這兩個問題實際上是須要綜合思考的,通常來講Nginx 502 Bad Gateway和php-fpm.conf的

設置有關,而Nginx 504 Gateway Time-out則是與nginx.conf的設置有關。
而正確的設置須要考慮服務器自身的性能和訪客的數量等多重因素。
以我目前的服務器爲例子CPU是奔四1.5G的,內存1GB,CENTOS的系統,訪客大概是50人左

右同時在線。
可是在線的人大都須要請求PHP-CGI進行大量的信息處理,所以我將nginx.conf設置爲:
fastcgi_connect_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;
fastcgi_buffer_size 128k;
fastcgi_buffers 8 128k;#8 128
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
fastcgi_intercept_errors on;
這裏最主要的設置是前三條,即
fastcgi_connect_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;
這裏規定了PHP-CGI的鏈接、發送和讀取的時間,300秒足夠用了,所以個人服務器不多出現

504 Gateway Time-out這個錯誤。最關鍵的是php-fpm.conf的設置,這個會直接致使502 Bad 

Gateway和504 Gateway Time-out。
下面咱們來仔細分析一下php-fpm.conf幾個重要的參數:
php-fpm.conf有兩個相當重要的參數,一個是」max_children」,另外一個是」

request_terminate_timeout」
個人兩個設置的值一個是」40″,一個是」900″,可是這個值不是通用的,而是須要本身計算的


計算的方式以下:
若是你的服務器性能足夠好,且寬帶資源足夠充足,PHP腳本沒有系循環或BUG的話你能夠直

接將」request_terminate_timeout」設置成0s。0s的含義是讓PHP-CGI一直執行下去而沒有時間

限制。而若是你作不到這一點,也就是說你的PHP-CGI可能出現某個BUG,或者你的寬帶不夠

充足或者其餘的緣由致使你的PHP-CGI可以假死那麼就建議你給」request_terminate_timeout」

賦一個值,這個值能夠根據你服務器的性能進行設定。通常來講性能越好你能夠設置越高,20

分鐘-30分鐘均可以。因爲個人服務器PHP腳本須要長時間運行,有的可能會超過10分鐘所以

我設置了900秒,這樣不會致使PHP-CGI死掉而出現502 Bad gateway這個錯誤。

而」max_children」這個值又是怎麼計算出來的呢?這個值原則上是越大越好,php-cgi的進程多

了就會處理的很快,排隊的請求就會不多。設置」max_children」也須要根據服務器的性能進行

設定,通常來講一臺服務器正常狀況下每個php-cgi所耗費的內存在20M左右,所以個人」

max_children」我設置成40個,20M*40=800M也就是說在峯值的時候全部PHP-CGI所耗內存在

800M之內,低於個人有效內存1Gb。而若是個人」max_children」設置的較小,好比5-10個,那

麼php-cgi就會「很累」,處理速度也很慢,等待的時間也較長。若是長時間沒有獲得處理的請求

就會出現504 Gateway Time-out這個錯誤,而正在處理的很累的那幾個php-cgi若是遇到了問

題就會出現502 Bad gateway這個錯誤。



nginx + keepalive 實現高可用負載均衡 

1、拓撲環境:

主nginx負載均衡器 192.168.166.203 
輔nginx負載均衡器 192.168.166.177
VIP地址 192.168.166.178
http://www.keepalived.org/download.html
tar -zxvf keepalived-1.2.1.tar.gz
cd keepalived-1.2.1
./configure --prefix=/usr/local/keepalived --sysconf=/etc
make && make install

cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/rc.d/init.d/
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
cp /usr/local/keepalived/sbin/keepalived /bin/
chkconfig --add keepalived
chmod 755 /etc/init.d/keepalived
chkconfig keepalived on
service keepalived start
二.修改配置文件爲如下內容: [master slave]
MASTER
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
xxx@xxx.com
}
notification_email_from xxx@xxx.com
smtp_server xxx.smtp.com
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script Monitor_Nginx {
script "/root/monitor_nginx.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER #(主機爲MASTER,備用機爲BACKUP)
interface eth0 #(HA監測網絡接口)

virtual_router_id 61 #(主、備機的virtual_router_id必須相同)
#mcast_src_ip 192.168.166.203 #(多播的源IP,設置爲本機外網IP,與VIP同一網卡)此項可

不設置
priority 90 #(主、備機取不一樣的優先級,主機值較大,備份機值較小,值越大優先級越高)
advert_int 1 #(VRRP Multicast廣播週期秒數)
authentication {
auth_type PASS #(VRRP認證方式)
auth_pass 1234 #(密碼)
}

track_script {
Monitor_Nginx #(調用nginx進程檢測腳本)
}
virtual_ipaddress {
192.168.166.178 #(VRRP HA虛擬地址)
}
}

###BACKUP方面只須要修改state爲BACKUP , priority比MASTER稍低就OK了
三:注:monitor_nginx.sh爲監控nginx進程的腳本,內容以下
#!/bin/bash
if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ]
then
/usr/local/nginx/sbin/nginx
sleep 5
if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ]
then
killall keepalived
fi
fi
#chmod +x monitor_nginx.sh
四.啓動keepalived
service keepalived start

/usr/local/keepalived/sbin/keepalived -D -f /etc/keepalived/keepalived.conf
五.測試步驟
1. 訪問VIP看是否可以正常訪問後端的web
2. 中止其中一個web看是否能將訪問轉到另外一臺上
3. 中止兩臺nginx上任何一個nginx進程看監控進程腳本是否會自動啓動nginx
4. 中止任何一臺nginx上的keepalived進程看另外一臺是否接管vip

track_interface的意思是將Linux中你想監控的網絡接口卡監控起來,當其中的一塊出現故障是

keepalived都將視爲路由器出現故障。
這裏請注意: virtual_router_id 61,同一組master/backup中,也就是若是你設置了多個VRRP

,同一組這個ID必須相同,否則啓動的時候主從都會把VIP給啓動了
keepalived 經過發送和接收組播包中的同一個virtual_router_id 的中的成員的存活,來肯定對

方的不可用,一旦檢測到對方的不可用,即會切換它的備份角色爲主。
即:當真實機192.168.166.177上的keepalived 檢測到 真實機192.168.166.203上的keepalived 

不可用時,177上將使用vip:192.168.166.178對外服務並由backup角色轉變爲master

keepalived+nginx實現 HA與負載均衡中keepalived負責實現HA功能,控制VIP(虛擬網絡地址)

轉移功能,nginx實現對realserver七層負載均衡功能,nginx提供代理服務和cache功能,DNS

服務能夠負責前段VIP的負載均衡。

 


keepalived的配置
192.168.200.1 keepalived配置
! Configuration File for keepalived

global_defs {
notification_email {
xxx@xxx.com
}
notification_email_from xxx@xxx.com
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_TEST_YDQ
}

vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 61
priority 150
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.200.101/24 dev eth0 label eth0:0
}
}

vrrp_instance VI_2 {
state BACKUP
interface eth0
virtual_router_id 62
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 2222
}
virtual_ipaddress {
192.168.200.102/24 dev eth0 label eth0:1
}
}


vrrp_instance VI_3 {
state BACKUP
interface eth0
virtual_router_id 63
priority 50
advert_int 1
authentication {
auth_type PASS
auth_pass 3333
}
virtual_ipaddress {
192.168.200.103/24 dev eth0 label eth0:1
}
}

nginx配置 :
user nobody nobody;                                                          
worker_processes 1;                                                           
                                                                              
#error_log logs/error.log;                                                    
#error_log logs/error.log notice;                                             
error_log logs/error.log debug;                                               
                                                                              
pid logs/nginx.pid;                                                           
                                                                              
                                                                              
events {                                                                      
use epoll;                                                                    
worker_connections 1024;                                                      
}                                                                             
                                                                              
                                                                              
http {                                                                        
include mime.types;                                                           
default_type application/octet-stream;                                        
                                                                              
log_format main '$remote_addr - $remote_user [$time_local] "$request" '       
'$status $body_bytes_sent "$http_referer" '                                   
'"$http_user_agent" "$http_x_forwarded_for"';                                 
                                                                              
access_log logs/access.log main;                                              
                                                                              
sendfile on;                                                                  
#tcp_nopush on;                                                               
                                                                              
#keepalive_timeout 0;                                                         
keepalive_timeout 65;                                                         
                                                                              
gzip on;                                                                      
gzip_min_length 1k;                                                           
gzip_buffers 6 16k;                                                           
gzip_http_version 1.1;                                                        
gzip_comp_level 2;                                                            
gzip_types text/plain application/x-javascript text/css application/xml;      
gzip_vary on;                                                                 
# location / {                                                                
# root html;                                                                  
# index index.html index.htm;                                                 
# }                                                                           
error_page 404 /404.html;                                                     
                                                                              
upstream www.test.com {                                                      
server 192.168.11.37:80;                                                      
server 192.168.11.38:80;                                                      
}                                                                             
                                                                              
server                                                                        
{                                                                             
listen 80;                                                                    
server_name www.test.com 192.168.166.178;                                    
index index.htm index.html;                                                   
#root /web/wwwroot;                                                           
                                                                              
location / {                                                                  
proxy_pass http://www.test.com;                                               proxy_next_upstream http_500 http_502 http_503 error timeout invalid_header;   proxy_set_header Host $host;                                                   proxy_set_header X-Real-IP $remote_addr;                                       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;                   include proxy.conf;                                                            }                                                                              log_format blog_test_com '$remote_addr - $remote_user [$time_local] $request ' '"$status" $body_bytes_sent "$http_referer" '                                  '"$http_user_agent" "$http_x_forwarded_for"';                                  access_log logs/blog_test_com;                                                 }                                                                              }                                            

相關文章
相關標籤/搜索