---
title: "RedHat Linux AS 5下Nginx的安装及Nginx+Tomcat负载均衡配置"
author: "shmayl"
date: "2010-11-11T16:30:40Z"
tags: ["Linux", "PHP", "RedHat", "Tomcat", "nginx"]
categories: ["操作系统"]
slug: "redhat-linux-as-5-nginx-nginx-tomcat"
draft: false
lastmod: "2010-11-30T12:49:54Z"
id: 808859
url: "https://shmayl.iteye.com/blog/808859"
---

一、软件准备

zlib-1.2.5.tar.gz\[支持gzip]，下载地址：http://www.zlib.net/

pcre-8.10.tar.gz\[支持rewrite module]，下载地址：[http://sourceforge.net/projects/pcre/files/](http://sourceforge.net/projects/pcre/files/)

openssl-1.0.0a.tar.tar\[支持ssl]，下载地址：[http://www.openssl.org/source/](http://www.openssl.org/source/)

下载**LATEST版本**

nginx-0.8.53.tar.gz，下载地址：http://nginx.org/en/download.html

二、安装过程

由于ssl暂时没有用到，所以没有安装

1、解压缩相关软件

\[root@localhost tools]# tar zxvf zlib-1.2.5.tar.gz

\[root@localhost tools]# tar zxvf pcre-8.10.tar.gz

\[root@localhost tools]# tar zxvf nginx-0.8.53.tar.gz

2、具体安装

\[root@localhost tools]# cd nginx-0.8.53

\[root@localhost nginx-0.8.53]# ./configure --prefix=/opt/nginx

--with-http\_realip\_module --with-http\_sub\_module --with-http\_flv\_module

--with-http\_dav\_module –with-http\_gzip\_static\_module --with-http\_stub\_status\_module

--with-http\_addition\_module --with-pcre=/opt/tools/pcre-8.10 --with-zlib=/opt/tools/zlib-1.2.5

\[root@localhost nginx-0.8.53]#make

\[root@localhost nginx-0.8.53]#make install

三、Nginx+Tomcat负载均衡配置

  1、架构描述：

     前端一台Nginx服务器做负载均衡，后端放两台\[当然可以多台]tomcat服务器，通过

Nginx转发到后面tomcat服务器，并且做动静分离

Nginx服务器IP:192.168.11.197

Tomcat01服务器IP:192.168.11.191

Tomcat02服务器IP:192.168.11.192

 

2、修改Nginx配置文件

\[root@localhost conf]# vi nginx.conf

#运行nginx所在的用户名和用户组

user  nobody nobody; 

#运行CPU个数，可以按照实际服务器来计算

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;

    include /opt/nginx/conf/proxy.conf;

    log\_format  main  '$remote\_addr - $remote\_user \[$time\_local] "$request" '

                      '$status $body\_bytes\_sent "$http\_referer" '

                      '"$http\_user\_agent" "$http\_x\_forwarded\_for"';

   #设定请求缓冲

   client\_header\_buffer\_size 1k;

   large\_client\_header\_buffers 4 4k;

   #设定可以使用gzip相关参数

   gzip on;

gzip\_comp\_level 7;

需要压缩的最小长度

   gzip\_min\_length 1100;

   gzip\_buffers 4 8k;

   #指定需要压缩的文件类型

   gzip\_types  text/plain application/javascript text/css text/xml

   gzip\_types text/plain;

   output\_buffers 1 32k;

   postpone\_output 1460;

   #设定访问日志

   access\_log  logs/access.log  main;

   client\_header\_timeout 3m;

   client\_body\_timeout 3m;

   send\_timeout 3m;

   sendfile on;

   tcp\_nopush on;

   tcp\_nodelay on;

 

 

   # sendfile        on;

   #tcp\_nopush     on;

 

   #keepalive\_timeout  0;

   #keepalive\_timeout  65;

 

   #gzip  on;

   upstream tomcat\_server{

     #设定转向Server，weight代表优先级，优先级高的先访问

     server  192.168.11.191:8080 weight=1;

     server  192.168.11.192:8080 weight=2;

    }

    server {

        listen       80;

        server\_name  localhost;

        charset gbk;

        access\_log  logs/host.access.log  main;

        location / {

            root /opt/www/root

            index  index.html index.htm index.jsp;

            proxy\_pass http://tomcat\_server;

        }

#设定查看Nginx状态的地址(非默认安装模块，需要在编译时加上

--with-http\_stub\_status\_module)  

location /status {  

    stub\_status            on;  

    access\_log            on;  

    auth\_basic            "status";  

    auth\_basic\_user\_file     conf/passwd;  

}

#访问[http://192.168.11.197/status](http://192.168.11.197/status)会提示输入账号

#htpasswd用法

#首先在conf/目录下建立passwd文件，具体命令：touch passwd

#htpasswd –cb passwd user password

 

        #css|js|ico|gif|jpg|jpeg|png|txt|html|htm|xml|swf|wav这些都是静态文件，

#但应分辨，js、css可能经常会变，过期时间应小一些，图片、

html基本不变，过期时间可以设长一些  

location ~* ^.+\\.(ico|gif|jpg|jpeg|png|html|htm)$ {  

    root         /opt/www/root;  

    access\_log   off;  

    expires      30d;  

}  

location ~* ^.+\\.(css|js|txt|xml|swf|wav)$ {  

    root         /opt/www/root;   

    access\_log   off;  

    expires      24h;  

}  

#注：location不包括?后面带的参数，所以以上正则可以

#匹配http://192.168.11.197/image/sxxx.jpg?a=xxx

        #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;

        }

 

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80

        #

        #location ~ \\.php$ {

        #    proxy\_pass   http://127.0.0.1;

        #}

 

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

        #

        #location ~ \\.php$ {

        #    root           html;

        #    fastcgi\_pass   127.0.0.1:9000;

        #    fastcgi\_index  index.php;

        #    fastcgi\_param  SCRIPT\_FILENAME  /scripts$fastcgi\_script\_name;

        #    include        fastcgi\_params;

        #}

 

        # deny access to .htaccess files, if Apache's document root

        # concurs with nginx's one

        #

        #location ~ /\\.ht {

        #    deny  all;

        #}

    }

 

 

    # another virtual host using mix of IP-, name-, and port-based configuration

    #

    #server {

    #    listen       8000;

    #    listen       somename:8080;

    #    server\_name  somename  alias  another.alias;

 

    #    location / {

    #        root   html;

    #        index  index.html index.htm;

    #    }

    #}

 

 

    # HTTPS server

    #

    #server {

    #    listen       443;

    #    server\_name  localhost;

 

    #    ssl                  on;

    #    ssl\_certificate      cert.pem;

    #    ssl\_certificate\_key  cert.key;

 

    #    ssl\_session\_timeout  5m;

 

    #    ssl\_protocols  SSLv2 SSLv3 TLSv1;

         # ssl\_ciphers 

ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;

    #    ssl\_prefer\_server\_ciphers   on;

 

    #    location / {

    #        root   html;

    #        index  index.html index.htm;

    #    }

    #}

 

}

在conf目录下创建proxy.conf文件，文件内容为

proxy\_redirect off;

proxy\_set\_header Host $host;

#获取真实IP

proxy\_set\_header X-Real-IP $remote\_addr;

#获取代理者的真实IP

proxy\_set\_header X-Forwarded-For $proxy\_add\_x\_forwarded\_for;

client\_max\_body\_size 10m;

client\_body\_buffer\_size 128k;

proxy\_connect\_timeout 90;

proxy\_send\_timeout 90;

proxy\_read\_timeout 90;

proxy\_buffer\_size 4k;

proxy\_buffers 4 32k;

proxy\_busy\_buffers\_size 64k;

proxy\_temp\_file\_write\_size 64k;

 

3、测试Nginx

测试nginx.conf文件是否正确

\[root@localhost sbin]# ./nginx -t -c conf/nginx.conf

the configuration file /opt/nginx/conf/nginx.conf syntax is ok

configuration file /opt/nginx/conf/nginx.conf test is successful

Nginx启动

\[root@localhost sbin]# ./nginx -c /opt/nginx/conf/nginx.conf

 

查看是否启动成功

\[root@localhost sbin]# ps aux|grep nginx |grep -v grep

root      4612  0.0  0.0   3792   472 ? Ss   Nov01   0:00 nginx: master process ./nginx

nobody    4613  0.0  0.1   4144  1284 ?    S    Nov01   0:05 nginx: worker process

 

出现上述两行代表启动成功

输入[http://192.168.11.197/](http://192.168.11.197/)测试下效果吧

 

 

 

4、Nginx启动、关闭脚本

#!/bin/sh  

#  

\# description: Starts, stops nginx  

#  

#chkconfig: 2345 20 80 

#dscription: Startup script for nginx webserver on CentOS. Place in /etc/init.d   

#  

\# Author: Touya  

set -e  

 

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/nginx  

DESC="nginx daemon" 

NAME=nginx  

DAEMON=/opt/nginx/sbin/$NAME  

CONFIGFILE=/opt/nginx/conf/nginx.conf  

PIDFILE=/opt/nginx/log/$NAME.pid  

SCRIPTNAME=/etc/init.d/$NAME  
   
\# Gracefully exit if the package has been removed.    
test -x $DAEMON || exit 0   
   
d\_start() {    
echo "Starting $DESC: $NAME"   
$DAEMON -c $CONFIGFILE || echo "already running"   
}    
   
d\_stop() {    
echo "Stopping $DESC: $NAME"   
test -f $PIDFILE && kill -QUIT \`cat $PIDFILE\`    
}    
   
d\_reload() {    
echo "Reloading $DESC configuration…"   
kill -HUP \`cat $PIDFILE\` || echo "can’t reload"   
}    
case "$1" in    
'start')    
    d\_start    
    echo "started."   
;;    
'stop')    
    d\_stop    
    echo "stoped."   
;;    
'reload')    
    d\_reload    
    echo "reloaded."   
;;    
'restart')    
    echo "Restarting $DESC: $NAME ..."   
    d\_stop    
    # One second might not be time enough for a daemon to stop,    
    # if this happens, d\_start will fail (and dpkg will break if    
    # the package is being upgraded). Change the timeout if needed    
    # be, or change d\_stop to have start-stop-daemon use --retry.    
    # Notice that using --retry slows down the shutdown process somewhat.    
    sleep 3   
    d\_start    
    echo "done."   
;;    
'list')    
    ps auxf | egrep '(PID|nginx)' | grep -v grep    
;;    
'test')    
    $DAEMON -t -c $CONFIGFILE    
;;    
\*)    
echo "Usage: $SCRIPTNAME {reload|list|test|start|stop|restart}" &gt;&2   
exit 3   
;;    
esac    
exit 0   
保存文件nginx ，拷贝到/etc/init.d下，并chmod  +x  /etc/init.d/nginx  
\[root@localhost init.d]# chkconfig --list nginx  
service nginx supports chkconfig, but is not referenced in any runlevel (run 'chkconfig --add nginx')  
增加后台服务  
\[root@localhost init.d]# chkconfig --add nginx  
\[root@localhost init.d]#  
接下可以用service nginx start|restart|stop来操作你的nginx服务器（restart时重新读入config）