使用Nginx+Apache搭配高性能高负载的服务器

谈到Linux下的web生产环境,大家就会想到apache这个开源服务器软件.apache可以整合大多数应用,比如jsp,php,cgi,Python等等,但是apache过于臃肿以及对静态文件响应过于缓慢让很多使用者感到头疼.而nginx作为新崛起的服务器软件,在很多方面超出apache,定位也很明确:高性能的 HTTP 和反向代理服务器.因而,本篇主要讲的是nginx作为前端,apache作为后端的应用环境搭建过程.

为什么使用nginx+php(fastcgi)作为生产环境?

  1. php(fastcgi)不够稳定,容易出现50x错误,在生成相对复杂的页面时没有优势,长时间占用也会使php-cgi进程死去.
  2. 在安全性,多用户多站点的权限问题比较严重.php(fastcgi)在应对多用户多站点往往捉襟见肘,不易于实施.
  3. 整合其他语言,apache表现得游刃有余.资源利用恰到好处.

为什么采用nginx做前端,apache作为后端的方案?nginx在处理静态内容上较apache是几倍或几十倍的差异,因而放在前面过滤静态内容是最为恰当的.同时nginx也是一个负载均衡器,低资源消耗,高性能转发是它的特点.经过nginx在前面的过滤,后端的apache需要处理的内容相对就比较少了.只需负责处理动态内容就可以了.在性能与稳定性的权衡下,使用nginx+apache搭配会让它们在各自擅长的领域展现自身的价值.

本教程以CentOS 6.0为环境.其他Linux发行版本暂未测试.nginx,php,apache,mysql,pureftpd均为最新稳定版.

获取操作系统源更新.

yum update
yum -y install gcc gcc-c++ bison patch unzip mlocate flex wget automake autoconf gd cpp gettext readline-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel libidn libidn-devel openldap openldap-devel openldap-clients openldap-servers nss_ldap expat-devel libtool libtool-ltdl-devel

如果系统默认安装了apache,请先卸载.执行:

yum remove httpd

下载最新稳定版的程序源码包,以下都是到官方网站或sourceforge下载的源码包.

cd /usr/local/src
wget http://dev.mysql.com/get/Downloads/MySQL-5.1/mysql-5.1.45.tar.gz/from/http://mysql.he.net/
wget http://www.apache.org/dist/httpd/httpd-2.2.15.tar.gz
wget http://stderr.net/apache/rpaf/download/mod_rpaf-0.6.tar.gz
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.1.tar.gz
wget http://sourceforge.net/projects/mcrypt/files/Libmcrypt/2.5.8/libmcrypt-2.5.8.tar.bz2/download
wget http://sourceforge.net/projects/mcrypt/files/MCrypt/2.6.8/mcrypt-2.6.8.tar.gz/download
wget http://sourceforge.net/projects/mhash/files/mhash/0.9.9.9/mhash-0.9.9.9.tar.bz2/download
wget http://www.php.net/get/php-5.2.13.tar.gz/from/this/mirror
wget http://www.lancs.ac.uk/~steveb/patches/php-mail-header-patch/php5-mail-header.patch
wget http://pecl.php.net/get/memcache-2.2.5.tgz
wget http://bart.eaccelerator.net/source/0.9.6/eaccelerator-0.9.6.tar.bz2
wget ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick.tar.gz
wget http://pecl.php.net/get/imagick-2.3.0.tgz
wget http://download.suhosin.org/suhosin-0.9.29.tgz
wget http://downloads2.ioncube.com/loader_downloads/ioncube_loaders_lin_x86.tar.gz
wget http://downloads.zend.com/optimizer/3.3.9/ZendOptimizer-3.3.9-linux-glibc23-i386.tar.gz
wget http://monkey.org/~provos/libevent-1.4.13-stable.tar.gz
wget http://memcached.googlecode.com/files/memcached-1.4.4.tar.gz
wget http://sourceforge.net/projects/pcre/files/pcre/8.01/pcre-8.01.tar.gz/download
wget http://nginx.org/download/nginx-0.7.65.tar.gz
wget http://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-1.0.28.tar.gz

一.安装Mysql.安装最新稳定版5.1.45版本,并没有采用最新开发版.

groupadd mysql -g 27
useradd mysql -u 27 -g 27 -c "MySQL Server" -d /var/lib/mysql -m
cd /usr/local/src
tar -zxf mysql-5.1.45.tar.gz
cd mysql-5.1.45
./configure --prefix=/usr/local/mysql --localstatedir=/var/lib/mysql --with-unix-socket-path=/var/lib/mysql/mysql.sock --with-mysqld-user=mysql --enable-assembler --enable-thread-safe-client --with-extra-charsets=all --with-big-tables --with-readline --with-ssl --with-embedded-server --enable-local-infile --with-plugins=partition,innodb_plugin,myisam,myisammrg
make && make install
cd ../

cp /usr/local/mysql/share/mysql/my-medium.cnf /etc/my.cnf
/usr/local/mysql/bin/mysql_install_db --user=mysql
chown -R mysql.mysql /var/lib/mysql
chgrp -R mysql /usr/local/mysql/.
cp /usr/local/mysql/share/mysql/mysql.server /etc/init.d/mysql
chmod u+x /etc/init.d/mysql
chkconfig --level 345 mysql on
echo "/usr/local/mysql/lib/mysql" >> /etc/ld.so.conf
echo "/usr/local/lib" >>/etc/ld.so.conf
ldconfig
ln -s /usr/local/mysql/lib/mysql /usr/lib/mysql
ln -s /usr/local/mysql/include/mysql /usr/include/mysql
ln -s /usr/local/mysql/bin/mysql_config /usr/bin/mysql_config
service mysql start
/usr/local/mysql/bin/mysqladmin -u root password root
service mysql restart
service mysql stop

二.编译安装apache(httpd).apache的执行用户为nobody.

cd /usr/local/src
tar -zxf httpd-2.2.15.tar.gz
cd httpd-2.2.15
./configure --prefix=/usr/local/apache --enable-headers --enable-mime-magic --enable-proxy --enable-rewrite --enable-ssl --enable-suexec  --disable-userdir --with-included-apr --with-mpm=prefork --with-ssl=/usr --with-suexec-caller=nobody --with-suexec-docroot=/ --with-suexec-gidmin=100 --with-suexec-logfile=/usr/local/apache/logs/suexec_log --with-suexec-uidmin=100 --with-suexec-userdir=public_html
make
make install
mkdir /usr/local/apache/domlogs
cp /usr/local/apache/bin/apachectl /etc/init.d/httpd

1.编辑/etc/init.d/httpd,在首行#!/bin/sh下添加:

# Startup script for the Apache Web Server
#
# chkconfig: - 85 15
# description: Apache is a World Wide Web server.  It is used to serve \
#              HTML files and CGI.
# processname: httpd
# pidfile: /usr/local/apache/logs/httpd.pid
# config: /usr/local/apache/conf/httpd.conf

ulimit -n 1024
ulimit -n 4096
ulimit -n 8192
ulimit -n 16384
ulimit -n 32768

保存退出.

2.配置apache配置参数文件httpd.conf,位于/usr/local/apache/conf/目录

cd /usr/local/apache/conf/
mv httpd.conf httpd.conf.bak
mkdir vhosts
vi httpd.conf

输入以下内容:

PidFile logs/httpd.pid
LockFile logs/accept.lock
ServerRoot "/usr/local/apache"
Listen 0.0.0.0:81
User nobody
Group nobody
ServerAdmin [email protected]
ServerName host.evlit.com

Timeout 300
KeepAlive Off
MaxKeepAliveRequests 100
KeepAliveTimeout 5
UseCanonicalName Off
AccessFileName .htaccess
TraceEnable Off
ServerTokens ProductOnly
FileETag None
ServerSignature Off
HostnameLookups Off

# LoadModule perl_module modules/mod_perl.so

DocumentRoot "/usr/local/apache/htdocs"
<Directory "/">
 Options ExecCGI FollowSymLinks Includes IncludesNOEXEC -Indexes -MultiViews SymLinksIfOwnerMatch
 Order allow,deny
 Allow from all
 AllowOverride All
</Directory>

<Directory "/usr/local/apache/htdocs">
 Options Includes -Indexes FollowSymLinks
 AllowOverride None
 Order allow,deny
 Allow from all
</Directory>

DefaultType text/plain
RewriteEngine on
AddType text/html .shtml
AddHandler cgi-script .cgi .pl .plx .ppl .perl
AddHandler server-parsed .shtml
<IfModule mime_module>
    TypesConfig conf/mime.types
    AddType application/perl .pl .plx .ppl .perl
    AddType application/x-img .img
    AddType application/x-httpd-php .php .php3 .php4 .php5 .php6
    AddType application/x-httpd-php-source .phps
    AddType application/cgi .cgi
    AddType text/x-sql .sql
    AddType text/x-log .log
    AddType text/x-config .cnf conf
    AddType text/x-registry .reg
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
    AddType text/html .shtml
    AddType application/x-tar .tgz
    AddType application/rar .rar
    AddType application/x-compressed .rar
    AddType application/x-rar .rar
    AddType application/x-rar-compressed .rar
    AddType text/vnd.wap.wml .wml
    AddType image/vnd.wap.wbmp .wbmp
    AddType text/vnd.wap.wmlscript .wmls
    AddType application/vnd.wap.wmlc .wmlc
    AddType application/vnd.wap.wmlscriptc .wmlsc
</IfModule>

<IfModule dir_module>
 DirectoryIndex index.html index.htm index.shtml index.php index.perl index.pl index.cgi
</IfModule>

<Files ~ "^error_log$">
 Order allow,deny
 Deny from all

 Satisfy All
</Files>

<FilesMatch "^\.ht">
 Order allow,deny
 Deny from all
 Satisfy All
</FilesMatch>

ErrorLog "logs/error_log"
LogLevel warn

<IfModule log_config_module>
 LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
 LogFormat "%h %l %u %t \"%r\" %>s %b" common

 <IfModule logio_module>
 LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
 </IfModule>
 CustomLog "logs/access_log" common
</IfModule>

<IfModule alias_module>
 ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/"
</IfModule>

<Directory "/usr/local/apache/cgi-bin">
 AllowOverride None
 Options None
 Order allow,deny
 Allow from all
</Directory>

<IfModule mpm_prefork_module>
 StartServers          3
 MinSpareServers       3
 MaxSpareServers       5
 MaxClients          150
 MaxRequestsPerChild   1024
</IfModule>

<IfModule mod_headers.c>
<FilesMatch "\.(html|htm|shtml)$">
Header set Cache-Control "max-age=3600, must-revalidate"
</FilesMatch>
</IfModule>

ReadmeName README.html
HeaderName HEADER.html

IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t

Include conf/extra/httpd-languages.conf

<Location /server-status>
 SetHandler server-status
 Order deny,allow
 Deny from all
 Allow from 127.0.0.1
</Location>
ExtendedStatus On

<Location /server-info>
 SetHandler server-info
 Order deny,allow
 Deny from all
 Allow from 127.0.0.1
</Location>

<IfModule ssl_module>
Listen 0.0.0.0:443
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl .crl
SSLCipherSuite ALL:!ADH:+HIGH:+MEDIUM:-LOW:-SSLv2:-EXP
SSLPassPhraseDialog  builtin
SSLSessionCache         dbm:/usr/local/apache/logs/ssl_scache
SSLSessionCacheTimeout  300
SSLMutex  file:/usr/local/apache/logs/ssl_mutex
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>

#Vhosts
NameVirtualHost 127.0.0.1:81
NameVirtualHost *

<VirtualHost 127.0.0.1:81 *>
 ServerName host.evlit.com
 DocumentRoot /var/www/html
 ServerAdmin [email protected]
</VirtualHost>

Include conf/vhosts/*

上述虚拟主机配置中出现的127.0.0.1请改为你本机公网IP.