Chinaunix首页 | 论坛 | 博客
  • 博客访问: 624566
  • 博文数量: 110
  • 博客积分: 3808
  • 博客等级: 中校
  • 技术积分: 1930
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-15 14:32
个人简介

声的伟大!

文章分类

全部博文(110)

文章存档

2014年(1)

2013年(2)

2012年(12)

2011年(81)

2010年(14)

分类: LINUX

2011-09-25 16:57:11

    Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。
                             
Nginx高性能:
为什么Nginx的性能要比Apache高得多?
这得益于Nginx使用了最新的epoll(Linux 2.6内核)和kqueue(freebsd)网络I/O模型,而Apache则使用的是传统的select模型。目前Linux下能够承受高并发访问的Squid、Memcached都采用的是epoll网络I/O模型。

  处理大量的连接的读写,Apache所采用的select网络I/O模型非常低效。
Nginx 是一个很牛的高性能Web和反向代理服务器, 它具有有很多非常优越的特性:
 
作为 Web 服务器:相比 Apache,Nginx 使用更少的资源,支持更多的并发连接,体现更高的效率,这点使 Nginx 尤其受到虚拟主机提供商的欢迎。在高连接并发的情况下,Nginx是Apache服务器不错的替代品: Nginx在美国是做虚拟主机生意的老板们经常选择的软件平台之一. 能够支持高达 50,000 个并发连接数的响应, 感谢Nginx为我们选择了 epoll and kqueue 作为开发模型.
Nginx作为负载均衡服务器: Nginx 既可以在内部直接支持 Rails 和 PHP 程序对外进行服务, 也可以支持作为 HTTP代理 服务器对外进行服务. Nginx采用C进行编写, 不论是系统资源开销还是CPU使用效率都比 Perlbal 要好很多. 。Nginx可作为7层负载均衡服务器来使用。
作为邮件代理服务器: Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器), Last.fm 描述了成功并且美妙的使用经验.
Nginx 是一个安装非常的简单 , 配置文件非常简洁(还能够支持perl语法), Bugs 非常少的服务器: Nginx 启动特别容易, 并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动. 你还能够不间断服务的情况下进行软件版本的升级 .
总体来说nginx的有以下八大优点:
1.高并发连接:官方测试能支撑5万并发连接,在实际生产环境中跑到2,~3W并发连接。
2.内存消耗少:在3W并发连接下,开启的10个NGINX进程才消耗150M内存(15M*10=150M)
3.配置文件非常简单:风格跟程序一样通俗易懂。
4.成本低廉:Nginx作为开源软件,可以免费使用,而购买F5 BIG-IP、NetScaler
等硬件负载均衡交换机则需要十多万至几十万人民币。
5.支持rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分发到不同的后端服务器群组。
6.内置的健康检查功能:如果Nginx Proxy后端的后台web服务器宕机了,不会音响前端访问。
7.节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头。
8.稳定性高:用于反向代理,宕机的概率微乎其微。

介绍这么多nginx 的优点.下面来具体实现下LEMP架构
nginx只是提供一个静态web服务,动态web服务还需要与PHP等脚本语言结合使用。如图所示:


客户端在访问动态页面时,因为apache和nginx只能提供静态解析,这是他们通过内置的cgi接口去寻找php等脚本语言,当需要用到数据部分时PHP会去调用后台MYSQL数据库中的数据,之后通过解析生成静态页面在返回apache/nginx服务器,再由此交付给客户端。

如果不清楚CGI和fastCGI笔者作以下简要说明:
 Perl、Python或者PHP原来在Web开发的时候应用得比较多,因为早期的web服务器(当然还包括Apache)内建了CGI(通用网关接口)接口。CGI能够以确定的方式让Web服务器在客户机的浏览器和外部应用程序之间交换数据。通过支持外部的、基于CGI的应用程序,Web开发人员能够引进动态要素。使用这种接口开发经过编译的应用程序相对来说比较复杂,但是,这种解释性的语言通常包括这种功能,或者是直接包括这种功能(如使用PHP),或者通过标准模块包括这种功能(如使用Perl和Python)。
FastCGI同CGI一样是一个WEB服务器与外部程序接口的标准,它是为解决CGI的性能问题而开发的一种技术。
CGI技术的性能缺陷:每当服务器收到一个对CGI程序请求时,服务器都将创建一个CGI程序的进程,CGI程序处理完请求后,将输出发给服务器或直接传回客户端,然后终止。
 
fastCGI对CGI技术进行了改良,一个fastCGI进程在WEB服务器启动时或在客户端第一次请求时创建,它处理完客户端请求后并不终止,而是等待处理下一个请求。另外fastCGI程序与CGI程序与服务器的交互方式也不同,CGI程序通过环境变量、命令行、标准输入输出进行交互,因此CGI程序进程必须与服务器进程在同一台物理计算机上,而fastCGI程序与服务器进程通过网络连接交互,因此fastCGI程序可以分布在不同的计算机上,这不但可以提高性能,同时也提高了系统的扩展能力。

下面开始源码架设LEMP架构:
笔者所使用的平台为RHEL5.4   kernel版本2.6.18-164
2011年9月21日笔者在nginx官方网站上获得的最新nginx版本信息:nginx-1.0.6.tar.gz
mysql-5.1.51.tar.gz
php-5.3.6.tar.bz2

一、获取相关开源程序:
1.yum -y install ntp vim-enhanced gcc gcc-c++ flex bison autoconf automake bzip2-devel \
ncurses-devel zlib-devel libjpeg-devel libpng-devel libtiff-devel freetype-devel libXpm-devel \
gettext-devel  pam-devel libtool libtool-l* openssl openssl-devel fontconfig-devel \
libxml2-devel curl-devel  libicu libicu-devel libmcrypt libmcrypt-devel libmhash libmhash-devel \
openldap openldap-devel nss_ldap openldap-clients openldap-servers \

 
#yum remove httpd mysql mysql-server php php-cli php-common php-devel php-gd  -y

2. 同步系统时间
#vim /etc/ntp.conf  //添加下面三行内容(19行下面添加)
 
server 3.cn.pool.ntp.org
server 3.asia.pool.ntp.org
server 0.asia.pool.ntp.org
 
# service ntpd stop
#ntpdate  cn.pool.ntp.org  //更新时间
#service ntpd start
chkconfig ntpd on

二、Install mysql 编译安装mysql:
# tar xvf mysql-5.1.51.tar.gz
# cd mysql-5.1.51
./configure \
--prefix=/usr/local/webserver/mysql \
--exec-prefix=/usr/local/webserver/mysql \
--with-mysqld-user=mysql \
--with-charset=utf8 \
--with-extra-charsets=all \
--with-pthread \
--enable-assembler \
--enable-thread-safe-client \
--with-big-tables \
--with-readline \
--with-ssl \
--with-embedded-server \
--enable-local-infile \
--with-plugins=innobase \

# make && make install

chmod +w /usr/local/webserver/mysql
chown -R mysql:mysql /usr/local/webserver/mysql

 附:以下为附加步骤,如果你想在这台服务器上运行MySQL数据库,则执行以下步骤。如果你只是希望让PHP支持MySQL扩展库,能够连接其他服务器上的MySQL数据库,那么,以下步骤无需执行。

创建MySQL数据库存放目录
mkdir -p /data/mysql/3306/data
chown -R mysql:mysql /data/mysql/


添加用户
groupadd –g 306 mysql
useradd –g mysql –u 306 –M –s /sbin/nologin mysql
chown -R mysql:mysql /data/mysql/3306/data

/usr/local/webserver/mysql/bin/mysql_install_db --basedir=/usr/local/webserver/mysql --datadir=/data/mysql/3306/data  --user=mysql

cp /usr/local/webserver/mysql/share/mysql/my-medium.cnf /etc/my.cnf
编辑/etc/my.cnf,内容仅供参考,根据实际需要配置

[client]
port    = 3306
socket  = /tmp/mysql.sock

[mysql]
#prompt="(\u:skyai1.cublog.cn:)[\d]> "
no-auto-rehash

[mysqld]
#character-set-server = utf8
replicate-ignore-db = mysql
replicate-ignore-db = test
replicate-ignore-db = information_schema
user    = mysql
port    = 3306
socket  = /tmp/mysql.sock
basedir = /usr/local/mysql
datadir = /data/mysql
open_files_limit    = 10240
back_log = 600
max_connections = 3000
max_connect_errors = 6000
table_cache = 614
external-locking = FALSE
max_allowed_packet = 32M
sort_buffer_size = 2M
join_buffer_size = 2M
thread_cache_size = 300
thread_concurrency = 8
query_cache_size = 32M
#query_cache_size = 512M
query_cache_limit = 2M
query_cache_min_res_unit = 2k
default-storage-engine = MyISAM
default_table_type = MyISAM
thread_stack = 192K
transaction_isolation = READ-COMMITTED
tmp_table_size = 246M
max_heap_table_size = 246M
long_query_time = 1
#long_query_time = 3
#log_short_format
log-bin = /data/mysql/mysql-bin
binlog_cache_size = 4M
binlog_format = MIXED
max_binlog_cache_size = 8M
max_binlog_size = 1G
expire_logs_days = 7
#expire_logs_days = 30
key_buffer_size = 256M
read_buffer_size = 1M
read_rnd_buffer_size = 16M
bulk_insert_buffer_size = 64M
myisam_sort_buffer_size = 128M
myisam_max_sort_file_size = 10G
myisam_repair_threads = 1
myisam_recover

skip-name-resolve
master-connect-retry = 10
slave-skip-errors = 1032,1062,126,1114,1146,1048,1396

server-id = 1

innodb_additional_mem_pool_size = 16M
innodb_buffer_pool_size = 1024M
innodb_data_home_dir = /data/mysqldata/
innodb_data_file_path = ibdata1:2000M;ibdata2:10M:autoextend
#innodb_data_file_path = ibdata1:50M:autoextend
innodb_log_group_home_dir = /data/mysqldata/
innodb_file_io_threads = 4
innodb_thread_concurrency = 8
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 16M
innodb_log_file_size = 128M
innodb_log_files_in_group = 3
innodb_max_dirty_pages_pct = 90
innodb_lock_wait_timeout = 120
innodb_file_per_table = 0
[mysqldump]
quick
max_allowed_packet = 32M


cp /usr/local/webserver/mysql/share/mysql/mysql.server /etc/init.d/mysqld
chmod 755 /etc/init.d/mysqld
chkconfig --add mysqld 
chkconfig --level 3 mysqld on
service mysqld start

测试数据库服务器
/usr/local/mysql/bin/mysql -uroot
root用户的默认密码是空
如出现标识符
mysql>
说明MySQL数据库安装成功,并且已经启动了!
为root用户设置密码
mysql>use mysql;
mysql>set password for root@localhost=password("centosmysqla#");
mysql>set password for root@127.0.0.1=password("centosmysqla#");
删除空帐户,查看帐户信息
mysql>delete from mysql.user where user='';
mysql>select user,host,password from mysql.user;
允许root用户远程登录
mysql>grant all privileges on *.* to root@'%' identified by 'centosmysqla#';
mysql>flush privileges;
mysql>quit


三、PHP的安装:
1.参考安装PHP[yum install php-snmp net-snmp net-snmp-libs net-snmp-utils net-snmp-devel libmcrypt mhash libevent]

# tar xvf php-5.3.6.tar.bz2
# cd php-5.3.6
./configure --prefix=/usr/local/webserver/php \
--with-mysql=/usr/local/webserver/mysql \
--with-mysqli=/usr/local/webserver/mysql/bin/mysql_config \
--with-pdo-mysql=/usr/local/webserver/mysql/ \
--enable-zip --enable-sqlite-utf8 --enable-sockets \
--enable-soap --enable-pcntl --enable-mbstring \
--enable-calendar --enable-bcmath \
--enable-exif --with-mhash --with-gd \
--with-png-dir --with-jpeg-dir --with-freetype-dir \
--with-libxml-dir --with-curl --with-curlwrappers \
--with-zlib \
--with-gettext=shared --with-xmlrpc=shared \
--with-ldap --with-ldap-sasl \
--with-libxml-dir \
--with-iconv \
--with-openssl \
--enable-mbregex \
--with-snmp \
--enable-gd-native-ttf  \
--disable-debug \
--with-mcrypt \
--enable-fpm \

make
make install
cp php.ini-development /usr/local/webserver/php/etc/php.ini

安装完毕【主意这个参数在此可以不加 -enable-fastcgi 其他之前的版本需要加上】

2.编译安装PHP5扩展模块
⑴memcache的安装
# tar xvf libevent-2.0.12-stable.tar.gz
# cd libevent-2.0.12-stable
./configure --prefix=/usr
make
make install

⑵、测试libevent是否安装成功

⑶安装memcached,同时需要安装中指定libevent的安装位置
# tar xvf memcached-1.4.7.tar.gz
cd memcached-1.4.7
./configure --with-libevent=/usr
make && make install

安装完成后会把memcached 自动放到 /usr/local/bin/memcached

⑷测试是否成功安装memcached
    ls -al /usr/local/bin/mem*
-rwxr-xr-x 1 root root 211656 Sep 21 14:30 /usr/local/bin/memcached

⑸安装Memcache的PHP扩展
①安装PHP的memcache扩展

tar vxzf memcache-2.2.5.tgz
cd memcache-2.2.5
/usr/local/webserver/php/bin/phpize
./configure --enable-memcache --with-php-config=/usr/local/webserver/php/bin/php-config --with-zlib-dir
make
make install

②上述安装完后会有类似这样的提示:

Installing shared extensions:     /usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20090626/

③把php.ini中的extension_dir = “./”修改为

extension_dir = “/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20090626/”

④添加一行来载入memcache扩展:extension=memcache.so


安装APC

当前我用的是APC-3.1.9 stable ,用户自己到 下载最新版。
①安装

    wget
    tar xzvf APC-3.1.9.tgz
    /usr/local/webserver/php/bin/phpize
    ./configure --enable-apc --enable-apc-mmap --with-php-config=/usr/local/webserver/php/bin/php-config --prefix=/usr/local/apc
    make && make install

注:安装编译后检查相应目录:

    ll /usr/local/webserver/php/lib/php/extensions/no-debug-zts-20090626/
    -rwxr-xr-x 1 root root 416628 12-15 17:13 apc.so

安装成功!

②配置/etc/php.ini

    vi /usr/local/webserver/php/etc/php.ini

shift+g到最末行,末尾加入

    [apc]
    extension= "apc.so"
    apc.enabled = 1
    apc.cache_by_default = on
    apc.shm_segments = 1
    apc.shm_size = 128M
    apc.ttl = 7200
    apc.user_ttl = 7200
    apc.num_files_hint = 0
    apc.write_lock = On

然后把APC目录下的apc.php复制到可以访问的目录

    cp /root/APC-3.0.19/apc.php /data/html/www 进行下面的测试


四、NGINX的安装:
yum install pcre pcre-devel

/usr/sbin/groupadd www
/usr/sbin/useradd -g www www
mkdir -p /data/html/blog
chmod +w /data/html/blog
chown -R www:www /data/html/blog
mkdir -p /data/html/www
chmod +w /data/html/www
chown -R www:www /data/html/www
# mkdir /usr/local/webserver/nginx/logs  #创建日志存放目录

# tar xvf nginx-1.0.6.tar.gz
# cd nginx-1.0.6

./configure                                                 
--prefix=/usr/local/webserver/nginx \
--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/ \

编译完成后
make && make install

编译安装完成后为了让nginx开机启动,笔者提供个systemV风格的脚本
vim /etc/init.d/nginxd

#!/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


保存退出 并给/etc/init.d/nginxd 赋予执行权限
chmod +x /etc/init.d/nginxd
chkconfig --add nginxd        ##让入开机启动选项中
chkconfig nginxd on          #让其开机自动启动
service nginxd  start       #立即启动nginx 服务



全部安装工作准备已经完成,剩下进行一些配置.
修改# vim /usr/local/webserver/php/etc/php-fpm.conf
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35

只需要把蓝色部分前面的注释去掉,修改完成,试着启动
/usr/local/webserver/php/sbin/php-fpm &  
启动后用netstat -tnlp 查看 如果有如图所示端口 测表示正常启动



如需要开机自动启动 则可以添加到/etc/rc.d/rc.local中
vim /etc/rc.d/rc.local
在空白行添加   /usr/local/webserver/php/sbin/php-fpm &  

创建Nginx配置文件
①、在/etc/nginx/目录中创建nginx.conf文件:
rm –f /etc/nginx/nginx.conf
vim /etc/nginx/nginx.conf

user  www www;
worker_processes 8;
error_log  /usr/local/webserver/nginx/logs/error.log  crit;
pid        /usr/local/webserver/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535/51200;
events
{
  use epoll;
  worker_connections 65535/51200;
}
http
{
  include      mime.types;
default_type  application/octet-stream;
#指定字符集,如果一个网站有多个字符集,请不要随便设置,应让程序员在HTML代码中通过Meta标签设置
#charset    utf-8;  
error_page  400 404 403 500 502 503 http://blog.mgcrazy.com;  
server_names_hash_bucket_size 128;
client_header_buffer_size 2k;
large_client_header_buffers 4 4k;
client_max_body_size 8m;
sendfile on;
tcp_nopush        on;
keepalive_timeout 60;
fastcgi_cache_path /usr/local/webserver/nginx/fastcgi_cache levels=1:2
keys_zone=TEST:10m
inactive=5m;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 4k;
fastcgi_buffers 8 4k;
fastcgi_busy_buffers_size 8k;
fastcgi_temp_file_write_size 8k;
##如下设置fastcGI_cache缓存,加速你的web站点!
fastcgi_cache TEST;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_key
open_file_cache max=204800 inactive=20s;
open_file_cache_min_uses 1;
open_file_cache_valid 30s;
tcp_nodelay on;

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

##设置301跳转,让二级域名跳转到你规定的url;
  server
  {
    listen       80;
    server_name blog.mgcrazy.com wgkgood.gicp.net linux.mgcrazy.com;
           if ($host = 'wgkgood.gicp.net' ) {
    rewrite ^/(.*)$ http://blog.mgcrazy.com/$1 permanent;  
}
    if ($host = 'linux.mgcrazy.com' ) {
    rewrite ^/(.*)$ http://blog.mgcrazy.com/$1 permanent;
}

    index index.php index.htm index.html;
    root  /data/html/www;
    #limit_conn   crawler  20;
    location ~ .*\.(php|php5)?$
    {
      #fastcgi_pass  unix:/tmp/php-cgi.sock;
      fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include fcgi.conf;
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
      expires      30d;
    }
    location ~ .*\.(js|css)?$
    {
      expires      1h;
    }
    log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
              '$status $body_bytes_sent "$http_referer" '
              '"$http_user_agent" $http_x_forwarded_for';
    access_log  /usr/local/webserver/nginx/logs/access.log  access;
      }
}


创建fcgi.conf文件内容如下
# vim /etc/nginx/fcgi.conf

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;


重启nginx服务即可访问

五、优化Linux内核参数,根据实际情况设定,参考国内Nginx大牛张宴的博客
vi /etc/sysctl.conf

  在末尾增加以下内容:
引用
# Add
net.ipv4.tcp_max_syn_backlog = 65536
net.core.netdev_max_backlog =  32768
net.core.somaxconn = 32768

net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216

net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2

net.ipv4.tcp_tw_recycle = 1
#net.ipv4.tcp_tw_len = 1
net.ipv4.tcp_tw_reuse = 1

net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_max_orphans = 3276800

#net.ipv4.tcp_fin_timeout = 30
#net.ipv4.tcp_keepalive_time = 120
net.ipv4.ip_local_port_range = 1024  65535


  使配置立即生效:
/sbin/sysctl –p


六、在不停止Nginx服务的情况下平滑变更Nginx配置:
1.    修改/etc/nginx/nginx.conf配置文件后,请执行以下命令检查配置文件是否正确:
# /usr/sbin/nginx –t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfu

2、这时,输入以下命令查看Nginx主进程号:
ps -ef | grep "nginx: master process" | grep -v "grep" | awk -F ' ' '{print $2}'

  屏幕显示的即为Nginx主进程号,例如:
[root@localhost logs]# ps -ef | grep "nginx: master process" | grep -v "grep" | awk -F ' ' '{print $2}'
4384

这时,执行以下命令即可使修改过的Nginx配置文件生效:
kill -HUP 4384

或者无需这么麻烦,找到Nginx的Pid文件:
kill -HUP `cat /usr/local/webserver/nginx/nginx.pid`

七、编写每天定时切割Nginx日志的脚本
Vim /usr/sbin/cut_nginx_log.sh

#!/bin/bash
# This script run at 00:00

# The Nginx logs path
logs_path="/usr/local/webserver/nginx/logs/"

mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path}access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_$(date -d "yesterday" +"%Y%m%d").log
kill -USR1 `cat /usr/local/webserver/nginx/nginx.pid`

2、设置crontab,每天凌晨00:00切割nginx访问日志
crontab -e

输入以下内容:
00 00 * * * /bin/bash  /usr/sbin/cut_nginx_log.sh


NGINX支持shtml



到此基本LNMP架构已经结束,以待后续...


安装的过程中所遇错误:





NGINX其他配置说明:
1.    虚拟主机
server
{
listen 80;
server_name blog.mgcrazy.com  mgcrazy.com *.mgcrazy.com;
access_log  /usr/local/webserver/nginx/logs/access.log combined;
location /
{
  index index.php index.html index.htm index.shtml;
  root /data/html/www;
}
}
   

2.Nginx的自动列目录配置
我们经常看到一些开源软件的下载页面是能够自动列目录的,这一功能Apache可以实现,Nginx同样可以实现,前提条件是当前目录下不存在用index指令设置的默认首页文件。如果需要在莫一虚拟主机的location / {…….}
location / {
  autoindex on;
}

另外,还有两项跟自动列目录相关的指令,分别为:
autoindex_exact_size [ on | off ]
设定索引时文件大小的单位(B、KB、MB、或GB)
autoindex_localtime [ on | off ]
开启以本地时间来显示文件时间的功能。默认为关(GMT时间)。

3.Nginx与JSP(Tomcat)在Linux上的安装、配置


3.1Tomcat和JDK的安装
在Linux上,我们首先安装JDK。JDK可以在以下网址下载:


下载完成后,修改jdk-6u27-linux-64.bin的文件的属性为可执行,然后安装可执行程序JDK:
chmod +x jdk-6u27-linux-64.bin
./ jdk-6u27-linux-64.bin
当前提示“Do you agree to the above license terms?[yes or no]”时,输入“yes”。安装完成后,执行以下语句:
mv jdk1.6.0_27 /usr/local/jdk
vim /etc/profile
在文件末尾增加以下内容:
export JAVA_HOME=”/usr/local/jdk”
export PATH=$PATH:$JAVA_HOME/bin
export CLASSPATH=$JAVA_HOME/lib
export CATALINA_HOME=/usr/local/tomcat
保存并退出,执行以下命令使配置生效:
. /etc/profile

安装完成JDK之后,按照以下步骤安装Tomcat二进制版本:

# tar xvf apache-tomcat-6.0.33-src.tar.gz
# mv apache-tomcat-6.0.33-src /usr/local/tomcat
# cp -rf /usr/local/tomcat/webapps/* /data/html/www/
# vim /usr/local/tomcat/conf/server.xml
查找appBase="webapps",修改为appBase="/data/html/www"即为您的网页根目录。
安装完成之后,启动Tomcat,默认监听的是8080端口:
/usr/local/tomcat/bin/startup.sh
停止Tomcat可以使用以下命令:
/usr/local/tomcat/bin/shutdown.sh

3.2Nginx与Tomcat的配置
nginx.conf 配置文件内容,在配置文件中,静态HTML网页、图片、JS、CSS、Flash等使用Nginx来处理,以便得到更快的速度,文件扩展名为.jsp、.do的请求,由Nginx反向代理Tomcat HTTP服务器来处理:



4.Nginx负载均衡和反向代理的配置与优化。
Nginx负载均衡,DNS轮询,智能DNS,基于硬件的有:四/七层负载均衡交换机,软件:四层的LVS,七层的Nginx,L7SW(layer7 switching)、HAProxy等。Nginx的反向代理负载均衡能够很好的支持虚拟主机,可配置性很强,可以按轮询、IP哈希、URL哈希等、权重等多种方式对后端的服务器做负载均衡,同时还支持后端服务器的健康检查。

user  www www;
worker_processes 8;
error_log  /usr/local/webserver/nginx/logs/error.log  crit;
pid        /usr/local/webserver/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 51200;
events
{
  use epoll;
  worker_connections 51200;
}

http
{
  include      mime.types;
default_type  application/octet-stream;
#charset    utf-8;
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;

sendfile on;
#tcp_nopush on;
keepalive_timeout 30;

tcp_nodelay on;

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;

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

#limit_zone  crawler  $binary_remote_addr  10m;

#允许客户端请求的最大单个文件的字节数
client_max_body_size 300m;

#缓冲区代理缓冲客户端请求的最大字节数,可以理解为先保存到本地再传给用户
client_body_buffer_size 128k;

#跟后端服务器连接的超时时间
proxy_connect_timeout 600;

#连接成功后_等候后端服务器响应时间_其实已经进入后端排队之中等候处理
proxy_read_timeout 600;

#后端服务器数据回传时间_就是在规定时间内后端服务器必须传完所有数据
proxy_send_timeout 600;

#代理请求缓存区_这个缓存区间会保存用户的头信息以供Nginx进程规划处理一般只要能保存下头信息即可
proxy_buffer_size 16k;

#同上 告诉Nginx保存单个用的几个buffer最大用多大空间
proxy_buffers 4 32k;

#如果系统很忙的时候可以申请最大的proxy_buffers官方推荐*2
proxy_busy_buffers_size 64k;

#proxy缓存临时文件的大小
proxy_temp_file_write_size 64k;

upstream php_server_pool {
    server 192.168.1.10:80 weight=4 max_fails=2 fail_timeout=30s;
    server 192.168.1.11:80 weight=4 max_fails=2 fail_timeout=30s;
    server 192.168.1.12:80 weight=4 max_fails=2 fail_timeout=30s;
}

upstream message_server_pool {
    server 192.168.1.13:3245;
    server 192.168.1.14:3245 down;
}

upstream bbs_server_pool {
    server 192.168.1.15:80 weight=1 max_fails=2 fail_timeout=30s;
    server 192.168.1.16:80 weight=1 max_fails=2 fail_timeout=30s;
    server 192.168.1.17:80 weight=1 max_fails=2 fail_timeout=30s;
    server 192.168.1.1:80 8weight=1 max_fails=2 fail_timeout=30s;
}

#第一个虚拟主机,反向代理php_server_pool这组服务器
server
{
    listen 80;
    server_name
    location /
    {
        #如果后端的服务器返回502、504、执行超时错误,自动将请求转发到upstream负载均衡池中德另一台服务器,实现故障转移
        proxy_next_upstream http_502 http_504 error timeout invalid_header;
        proxy_pass
        proxy_set_header Host
        proxy_set_header X-Forwarded-For $remote_addr;
    }
    access_log /usr/local/webserver/nginx/logs/
}

#第二个虚拟主机
server
{
    listen 80;
    server_name
    #访问地址,反向代理message_server_pool这组服务器
    location /message/
    {
        proxy_pass
        proxy_set_header Host $host;
    }
    #访问除了/message/之外的***地址,反向代理php_server_pool这组服务器
    location /
    {
        proxy_pass
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
    access_log /usr/local/webserver/apache/logs/
   
}

#第三个虚拟主机
Server {
    listen 80;
    server_name bbs.yourdomain.com *.bbs.yourdomain.com;
    location /
    {
        proxy_pass
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
    access_log off;
}
}


5.实现SSL配置




6.采用Nginx搭建FLV视频服务器
6.1采用Nginx的LLV Stream 模块搭建HTTP下载方式的FLV视频服务器
在编译时加上—with-http_flv_module
然后,在nginx.conf配置文件中配置存储FLV视频文件的虚拟主机:

server
{
    listen 80;
    server_name flv.domain.com;
    index.shtml index.html index.htm;
    root /data/html/flv_files;
   
    limit_rate_after 3m;
    limit_rate 512k;

    location ~ \.flv
    {
        flv;
    }
    access_log off;
}


该吃饭了,以待后续...
阅读(2685) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~