Nginx0.8.x+PHP5.2.14+Mysql5.5.3在小内存VPS服务器上的安装配置与优化


注:该文档大量参考了 张宴 的两篇原创文章,在此表示由衷的感谢。

两篇文章链接如下:
http://blog.s135.com/post/375/
http://blog.s135.com/nginx_php_v6/

但是,由于我所采用的Nginx,Php,Mysql的版本都要比张宴在第一篇文章中的版本高一些,所以在实际的安装过程中,并非一帆风顺,主要是在编译的参数和配置文件方面出现了一些问题,好在最后都得以解决。因此,我将整个过程记录了下来,以供大家参考。

安装步骤:
(系统要求:Linux 2.6+ 内核,本文中的Linux操作系统为CentOS 5.5)

一、获取相关开源程序:
1、利用CentOS Linux系统自带的yum命令安装、升级所需的程序库:
sudo -s -H
LANG=C
yum -y install gcc gcc-c++ autoconf 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 krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers

2、下载程序源码包:
mkdir -p /root/install
cd /root/install
wget http://sysoev.ru/nginx/nginx-0.8.46.tar.gz
wget http://www.php.net/get/php-5.2.14.tar.gz/from/this/mirror
wget http://php-fpm.org/downloads/php-5.2.14-fpm-0.5.14.diff.gz
wget http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.3-m3.tar.gz/from/http://mysql.he.net/
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.1.tar.gz
wget "http://downloads.sourceforge.net/mcrypt/libmcrypt-2.5.8.tar.gz?modtime=1171868460&big_mirror=0"
wget "http://downloads.sourceforge.net/mcrypt/mcrypt-2.6.8.tar.gz?modtime=1194463373&big_mirror=0"
wget http://pecl.php.net/get/memcache-2.2.5.tgz
wget "http://downloads.sourceforge.net/mhash/mhash-0.9.9.9.tar.gz?modtime=1175740843&big_mirror=0"
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.10.tar.gz
wget http://bart.eaccelerator.net/source/0.9.6.1/eaccelerator-0.9.6.1.tar.bz2
wget http://pecl.php.net/get/PDO_MYSQL-1.0.2.tgz
wget http://blog.s135.com/soft/linux/nginx_php/imagick/ImageMagick.tar.gz
wget http://pecl.php.net/get/imagick-2.3.0.tgz

二、安装PHP 5.2.14(FastCGI模式)
1、编译安装PHP 5.2.14所需的支持库:
tar zxvf libiconv-1.13.1.tar.gz
cd libiconv-1.13.1/
./configure --prefix=/usr/local
make
make install
cd ../

tar zxvf libmcrypt-2.5.8.tar.gz
cd libmcrypt-2.5.8/
./configure
make
make install
/sbin/ldconfig
cd libltdl/
./configure --enable-ltdl-install
make
make install
cd ../../

tar zxvf mhash-0.9.9.9.tar.gz
cd mhash-0.9.9.9/
./configure
make
make install
cd ../

ln -s /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la
ln -s /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so
ln -s /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4
ln -s /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8
ln -s /usr/local/lib/libmhash.a /usr/lib/libmhash.a
ln -s /usr/local/lib/libmhash.la /usr/lib/libmhash.la
ln -s /usr/local/lib/libmhash.so /usr/lib/libmhash.so
ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2
ln -s /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1
ln -s /usr/local/bin/libmcrypt-config /usr/bin/libmcrypt-config

tar zxvf mcrypt-2.6.8.tar.gz
cd mcrypt-2.6.8/
/sbin/ldconfig
./configure
make
make install
cd ../

2、编译安装MySQL 5.5.3-m3
#配置优化#使用以下参数编译安装的 MySQL 5.5 默认支持4种存储引擎:CSV、MRG_MYISAM、MEMORY、MyISAM,不支持InnoDB存储引擎。由于内存有限,而InnoDB耗费的内存较大,这里推荐使用MyISAM存储引擎。
/usr/sbin/groupadd mysql
/usr/sbin/useradd -g mysql mysql
tar zxvf mysql-5.5.3-m3.tar.gz
cd mysql-5.5.3-m3/
./configure --prefix=/web/mysql/ --enable-assembler --with-extra-charsets=complex --enable-thread-safe-client --with-big-tables --with-readline --with-ssl --with-embedded-server --enable-local-infile
make && make install
chmod +w /web/mysql
chown -R mysql:mysql /web/mysql
cd ../

3、初始化MySQL数据库
①、创建MySQL数据库存放目录
mkdir -p /mysql/data/
mkdir -p /mysql/binlog/
mkdir -p /mysql/relaylog/
mkdir -p /mysql/etc/
chown -R mysql:mysql /mysql/

②、以mysql用户帐号的身份建立数据表
/web/mysql/bin/mysql_install_db --basedir=/web/mysql --datadir=/mysql/data --user=mysql

③、创建my.cnf配置文件
#配置优化#通过调整配置文件参数实现对MySQL的优化。

vi /mysql/etc/my.cnf

输入以下内容:

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

[mysql]
no-auto-rehash

[mysqld]
user    = mysql
port    = 3306
bind-address = 127.0.0.1
socket  = /tmp/mysql.sock
basedir = /web/mysql
datadir = /mysql/data
open_files_limit    = 600
back_log = 20
max_connections = 100
max_connect_errors = 200
table_cache = 60
external-locking = FALSE
max_allowed_packet = 16M
sort_buffer_size = 128K
join_buffer_size = 128K
thread_cache_size = 10
query_cache_size = 0M
query_cache_limit = 2M
query_cache_min_res_unit = 2k
thread_stack = 192K
transaction_isolation = READ-UNCOMMITTED
tmp_table_size = 512K
max_heap_table_size = 32M
slow-query-log-file = /mysql/log/slow.log
log-error = /mysql/log/error.log
long_query_time = 1
server-id = 1
log-bin = /mysql/log/binlog
binlog_cache_size = 2M
max_binlog_cache_size = 4M
max_binlog_size = 512M
expire_logs_days = 7
key_buffer_size = 4M
read_buffer_size = 1M
read_rnd_buffer_size = 2M
bulk_insert_buffer_size = 2M
myisam_sort_buffer_size = 4M
myisam_repair_threads = 1
myisam_recover

[mysqldump]
quick
max_allowed_packet = 16M

④、创建管理MySQL数据库的shell脚本:
vi /mysql/mysql

输入以下内容(这里的用户名admin和密码12345678接下来的步骤会创建):

#!/bin/sh

mysql_username="admin"
mysql_password="12345678"

function_start_mysql()
{
    printf "Starting MySQL...\n"
    /bin/sh /web/mysql/bin/mysqld_safe --defaults-file=/mysql/etc/my.cnf 2>&1 > /dev/null &
}

function_stop_mysql()
{
    printf "Stoping MySQL...\n"
    /web/mysql/bin/mysqladmin -u ${mysql_username} -p${mysql_password} -S /tmp/mysql.sock shutdown
}

function_restart_mysql()
{
    printf "Restarting MySQL...\n"
    function_stop_mysql
    sleep 5
    function_start_mysql
}

function_kill_mysql()
{
    kill -9 $(ps -ef | grep 'bin/mysqld_safe' | awk '{printf $2}')
    kill -9 $(ps -ef | grep 'libexec/mysqld' | awk '{printf $2}')
}

if [ "$1" = "start" ]; then
    function_start_mysql
elif [ "$1" = "stop" ]; then
    function_stop_mysql
elif [ "$1" = "restart" ]; then
    function_restart_mysql
elif [ "$1" = "kill" ]; then
    function_kill_mysql
else
    printf "Usage: /mysql/mysql {start|stop|restart|kill}\n"
fi

⑤、赋予shell脚本可执行权限:
chmod +x /mysql/mysql

⑥、启动MySQL:
/mysql/mysql start

⑦、通过命令行登录管理MySQL服务器(提示输入密码时直接回车):
/web/mysql/bin/mysql -u root -p -S /tmp/mysql.sock

⑧、输入以下SQL语句,创建一个具有root权限的用户(admin)和密码(12345678):
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' IDENTIFIED BY '12345678';
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'127.0.0.1' IDENTIFIED BY '12345678';

⑨、(可选)停止MySQL:
/mysql/mysql stop

4、编译安装PHP(FastCGI模式)
tar zxvf php-5.2.14.tar.gz
gzip -cd php-5.2.14-fpm-0.5.14.diff.gz | patch -d php-5.2.14 -p1
cd php-5.2.14/
./configure --prefix=/web/php --with-config-file-path=/web/php/etc --with-mysql=/web/mysql --with-mysqli=/web/mysql/bin/mysql_config --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-discard-path --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fastcgi --enable-fpm --enable-force-cgi-redirect --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-ldap --with-ldap-sasl --with-xmlrpc --enable-zip --enable-soap
make ZEND_EXTRA_LIBS='-liconv'
make install
cp php.ini-dist /web/php/etc/php.ini
cd ../

5、编译安装PHP5扩展模块
tar zxvf memcache-2.2.5.tgz
cd memcache-2.2.5/
/web/php/bin/phpize
./configure --with-php-config=/web/php/bin/php-config
make
make install
cd ../

tar jxvf eaccelerator-0.9.6.1.tar.bz2
cd eaccelerator-0.9.6.1/
/web/php/bin/phpize
./configure --enable-eaccelerator=shared --with-php-config=/web/php/bin/php-config
make
make install
cd ../

tar zxvf PDO_MYSQL-1.0.2.tgz
cd PDO_MYSQL-1.0.2/
/web/php/bin/phpize
./configure --with-php-config=/web/php/bin/php-config --with-pdo-mysql=/web/mysql
make
make install
cd ../

tar zxvf ImageMagick.tar.gz
cd ImageMagick-6.5.1-2/
./configure
make
make install
cd ../

tar zxvf imagick-2.3.0.tgz
cd imagick-2.3.0/
/web/php/bin/phpize
./configure --with-php-config=/web/php/bin/php-config
make
make install
cd ../

6、修改php.ini文件
手工修改:查找/web/php/etc/php.ini中的extension_dir = "./"
修改为extension_dir = "/web/php/lib/php/extensions/no-debug-non-zts-20060613/"
并在此行后增加以下几行,然后保存:
extension = "memcache.so"
extension = "pdo_mysql.so"
extension = "imagick.so"

再查找output_buffering = Off
修改为output_buffering = On

再查找; cgi.fix_pathinfo=0
修改为cgi.fix_pathinfo=0,防止Nginx文件类型错误解析漏洞。

7、配置eAccelerator加速PHP:
#配置优化#php.ini 配置文件中关于eAcelerator的优化。只使用1M共享内存,删除所有在最后3600秒内无法存取的脚本缓存,用磁盘辅助进行缓存。
mkdir /web/eaccelerator_cache
vi /web/php/etc/php.ini

按shift+g键跳到配置文件的最末尾,加上以下配置信息:

[eaccelerator]
zend_extension="/web/php/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so"
eaccelerator.shm_size="1"
eaccelerator.cache_dir="/web/eaccelerator_cache"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="3600"
eaccelerator.shm_prune_period="3600"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
eaccelerator.keys = "disk_only"
eaccelerator.sessions = "disk_only"
eaccelerator.content = "disk_only"

8、创建www用户和组,以及供www.nginxs.com和heyLinux.com两个虚拟主机使用的目录:
/usr/sbin/groupadd www
/usr/sbin/useradd -g www www
mkdir -p /blog/eric
chmod +w /blog/eric
chown -R www:www /blog/eric
mkdir -p /blog/rainbow
chmod +w /blog/rainbow
chown -R www:www /blog/rainbow

9、创建php-fpm配置文件(php-fpm是为PHP打的一个FastCGI管理补丁,可以平滑变更php.ini配置而无需重启php-cgi):
在/web/php/etc/目录中创建php-fpm.conf文件:
rm -f /web/php/etc/php-fpm.conf
vi /web/php/etc/php-fpm.conf

输入以下内容(如果您安装 Nginx + PHP 用于程序调试,请将以下的0改为1,以便显示PHP错误信息,否则,Nginx 会报状态为500的空白错误页):

<?xml version="1.0" ?>
<configuration>

  All relative paths in this config are relative to php's install prefix

  <section name="global_options">

    Pid file
    <value name="pid_file">/web/php/logs/php-fpm.pid</value>

    Error log file
    <value name="error_log">/web/php/logs/php-fpm.log</value>

    Log level
    <value name="log_level">notice</value>

    When this amount of php processes exited with SIGSEGV or SIGBUS ...
    <value name="emergency_restart_threshold">10</value>

    ... in a less than this interval of time, a graceful restart will be initiated.                                                                                    
    Useful to work around accidental curruptions in accelerator's shared memory.
    <value name="emergency_restart_interval">1m</value>

    Time limit on waiting child's reaction on signals from master
    <value name="process_control_timeout">5s</value>

    Set to 'no' to debug fpm
    <value name="daemonize">yes</value>

  </section>

  <workers>

    <section name="pool">

      Name of pool. Used in logs and stats.
      <value name="name">default</value>

      Address to accept fastcgi requests on.
      Valid syntax is 'ip.ad.re.ss:port' or just 'port' or '/path/to/unix/socket'                                                                                      
      <value name="listen_address">/tmp/php-cgi.sock</value> #配置优化#将TCP模式改为Unix Socket模式

      <value name="listen_options">

        Set listen(2) backlog
        <value name="backlog">-1</value>

        Set permissions for unix socket, if one used.
        In Linux read/write permissions must be set in order to allow connections from web server.                                                               
        Many BSD-derrived systems allow connections regardless of permissions.
        <value name="owner"></value>
        <value name="group"></value>
        <value name="mode">0666</value>
      </value>

      Additional php.ini defines, specific to this pool of workers.
      <value name="php_defines">
        <value name="sendmail_path">/usr/sbin/sendmail -t -i</value>
        <value name="display_errors">1</value>
      </value>

      Unix user of processes
      <value name="user">www</value>

      Unix group of processes
      <value name="group">www</value>

      Process manager settings
      <value name="pm">

        Sets style of controling worker process count.
        Valid values are 'static' and 'apache-like'
        <value name="style">static</value>

        Sets the limit on the number of simultaneous requests that will be served.                                                                                
        Equivalent to Apache MaxClients directive.
        Equivalent to PHP_FCGI_CHILDREN environment in original php.fcgi
        Used with any pm_style.
        <value name="max_children">5</value> #配置优化#将启动的php-cgi进程数由原来的128个改为5个

        Settings group for 'apache-like' pm style
        <value name="apache_like">

          Sets the number of server processes created on startup.
          Used only when 'apache-like' pm_style is selected
          <value name="StartServers">20</value>

          Sets the desired minimum number of idle server processes.
          Used only when 'apache-like' pm_style is selected
          <value name="MinSpareServers">5</value>

          Sets the desired maximum number of idle server processes.
          Used only when 'apache-like' pm_style is selected
          <value name="MaxSpareServers">35</value>

        </value>

      </value>

      The timeout (in seconds) for serving a single request after which the worker process will be terminated                                                                                        
      Should be used when 'max_execution_time' ini option does not stop script execution for some reason                                                                                        
      '0s' means 'off'
      <value name="request_terminate_timeout">0s</value>

      The timeout (in seconds) for serving of single request after which a php backtrace will be dumped to slow.log file                                                                                        
      '0s' means 'off'
      <value name="request_slowlog_timeout">0s</value>

      The log file for slow requests
      <value name="slowlog">logs/slow.log</value>

      Set open file desc rlimit
      <value name="rlimit_files">65535</value>

      Set max core size rlimit
      <value name="rlimit_core">0</value>

      Chroot to this directory at the start, absolute path
      <value name="chroot"></value>

      Chdir to this directory at the start, absolute path
      <value name="chdir"></value>

      Redirect workers' stdout and stderr into main error log.
      If not set, they will be redirected to /dev/null, according to FastCGI specs                                                                                        
      <value name="catch_workers_output">yes</value>

      How much requests each process should execute before respawn.
      Useful to work around memory leaks in 3rd party libraries.
      For endless request processing please specify 0
      Equivalent to PHP_FCGI_MAX_REQUESTS
      <value name="max_requests">1024</value>

      Comma separated list of ipv4 addresses of FastCGI clients that allowed to connect.                                                                                        
      Equivalent to FCGI_WEB_SERVER_ADDRS environment in original php.fcgi (5.2.2+)                                                                                        
      Makes sense only with AF_INET listening socket.
      <value name="allowed_clients">127.0.0.1</value>

      Pass environment variables like LD_LIBRARY_PATH
      All $VARIABLEs are taken from current environment
      <value name="environment">
        <value name="HOSTNAME">$HOSTNAME</value>
        <value name="PATH">/usr/local/bin:/usr/bin:/bin</value>
        <value name="TMP">/tmp</value>
        <value name="TMPDIR">/tmp</value>
        <value name="TEMP">/tmp</value>
        <value name="OSTYPE">$OSTYPE</value>
        <value name="MACHTYPE">$MACHTYPE</value>
        <value name="MALLOC_CHECK_">2</value>
      </value>

    </section>

  </workers>

</configuration>

10、启动php-cgi进程,用户为www:
ulimit -SHn 65535
/web/php/sbin/php-fpm start

注:/web/php/sbin/php-fpm还有其他参数,包括:start|stop|quit|restart|reload|logrotate,修改php.ini后不重启php-cgi,重新加载配置文件使用reload。

三、安装Nginx 0.8.46
1、安装Nginx所需的pcre库:
tar zxvf pcre-8.10.tar.gz
cd pcre-8.10/
./configure
make && make install
cd ../

2、安装Nginx
tar zxvf nginx-0.8.46.tar.gz
cd nginx-0.8.46/
./configure --user=www --group=www --prefix=/web/nginx --with-http_stub_status_module --with-http_ssl_module
make && make install
cd ../

3、创建Nginx日志目录
mkdir -p /blog/logs
chmod +w /blog/logs/
chown -R www:www /blog/logs/

4、创建Nginx配置文件
①、在/web/nginx/conf/目录中创建nginx.conf文件:
rm -f /web/nginx/conf/nginx.conf
vi /web/nginx/conf/nginx.conf

输入以下内容:

user  www www;

#配置优化#Nginx每个进程耗费10M~12M内存,这里只开启2个Nginx进程,节省内存。
worker_processes 2;

error_log  /blog/logs/nginx_error.log  crit;

pid        /web/nginx/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;

events
{
  use epoll;
  worker_connections 65535;
}

http
{
  include       mime.types;
  default_type  application/octet-stream;

  #charset  gb2312;

  server_names_hash_bucket_size 128;
  client_header_buffer_size 32k;
  large_client_header_buffers 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 64k;
  fastcgi_buffers 4 64k;
  fastcgi_busy_buffers_size 128k;
  fastcgi_temp_file_write_size 128k;

#配置优化#对网页文件、CSS、JS、XML等启动gzip压缩,减少数据传输量,提高访问速度。
  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;

  server
  {
    listen       80;
    server_name  204.74.215.57;
    index index.html index.htm index.php;
    root  /blog;

    location ~ .*\.(php|php5)?$
    {
#配置优化#将Nginx与FastCGI的通信方式由TCP改为Unix Socket。TCP在高并发访问下比Unix Socket稳定,但Unix Socket速度要比TCP快。
      fastcgi_pass  unix:/tmp/php-cgi.sock;
      #fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include default_fcgi.conf;
    }

    log_format  default_access  '$remote_addr - $remote_user [$time_local] "$request" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" $http_x_forwarded_for';
    access_log  /blog/logs/default_access.log  default_access;
  }

  server
  {
    listen       80;
    server_name  www.nginxs.com nginxs.com *.nginxs.com;
    index index.html index.htm index.php;
    root  /blog/eric;

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

    location ~ .*\.(php|php5)?$
    {
#配置优化#将Nginx与FastCGI的通信方式由TCP改为Unix Socket。TCP在高并发访问下比Unix Socket稳定,但Unix Socket速度要比TCP快。
      fastcgi_pass  unix:/tmp/php-cgi.sock;
      #fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include eric_fcgi.conf;
    }

#配置优化#博客的图片较多,更改较少,将它们在浏览器本地缓存15天,可以提高下次打开我博客的页面加载速度。
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
      expires      15d;
    }

#配置优化#博客会加载很多JavaScript、CSS,将它们在浏览器本地缓存1天,访问者在看完一篇文章或一页后,再看另一篇文件或另一页的内容,无需从服务器再次下载相同的JavaScript、CSS,提高了页面显示速度。
    location ~ .*\.(js|css)?$
    {
      expires      1d;
    }    

    log_format  eric_access  '$remote_addr - $remote_user [$time_local] "$request" '
              '$status $body_bytes_sent "$http_referer" '
              '"$http_user_agent" $http_x_forwarded_for';
    access_log  /blog/logs/eric_access.log  eric_access;
      }

  server
  {
    listen       80;
    server_name  heylinux.com www.heylinux.com blog.heylinux.com heyrainbow.com www.heyrainbow.com blog.heyrainbow.com;
    index index.html index.htm index.php;
    root  /blog/rainbow;

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

    location ~ .*\.(php|php5)?$
    {
#配置优化#将Nginx与FastCGI的通信方式由TCP改为Unix Socket。TCP在高并发访问下比Unix Socket稳定,但Unix Socket速度要比TCP快。
      fastcgi_pass  unix:/tmp/php-cgi.sock;
      #fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include rainbow_fcgi.conf;
    }

#配置优化#博客的图片较多,更改较少,将它们在浏览器本地缓存15天,可以提高下次打开我博客的页面加载速度。
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
      expires      15d;
    }

#配置优化#博客会加载很多JavaScript、CSS,将它们在浏览器本地缓存1天,访问者在看完一篇文章或一页后,再看另一篇文件或另一页的内容,无需从服务器再次下载相同的JavaScript、CSS,提高了页面显示速度。
    location ~ .*\.(js|css)?$
    {
      expires      1d;
    }    

    log_format  rainbow_access  '$remote_addr - $remote_user [$time_local] "$request" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" $http_x_forwarded_for';
    access_log  /blog/logs/rainbow_access.log  rainbow_access;
  }

    server
  {
    listen  80;
    server_name  status.nginxs.com status.heylinux.com;

    location / {
    stub_status on;
    access_log   off;
    }
  }
}

②、在/web/nginx/conf/目录中创建fcgi.conf文件:
vi /web/nginx/conf/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;

然后为两个虚拟主机建立不同的fcgi.conf文件:
cp /web/nginx/conf/fcgi.conf /web/nginx/conf/eric_fcgi.conf
并修改“$document_root$fastcgi_script_name;” 为 "/blog/eric/$fastcgi_script_name;"
cp /web/nginx/conf/fcgi.conf /web/nginx/conf/rainbow_fcgi.conf
并修改“$document_root$fastcgi_script_name;” 为 "/blog/rainbow/$fastcgi_script_name;"

5、启动Nginx
ulimit -SHn 65535
/web/nginx/sbin/nginx

四、配置开机自动启动Nginx + PHP
vi /etc/rc.local

在末尾增加以下内容:
ulimit -SHn 65535
/web/php/sbin/php-fpm start
/web/nginx/sbin/nginx

五、优化Linux内核参数
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、修改/web/nginx/conf/nginx.conf配置文件后,请执行以下命令检查配置文件是否正确:
/web/nginx/sbin/nginx -t

如果屏幕显示以下两行信息,说明配置文件正确:
the configuration file /web/nginx/conf/nginx.conf syntax is ok
the configuration file /web/nginx/conf/nginx.conf was tested successfully

2、平滑重启:
对于Nginx 0.8.x版本,现在平滑重启Nginx配置非常简单,执行以下命令即可:
/web/nginx/sbin/nginx -s reload

七、编写每天定时切割Nginx日志的脚本
1、创建脚本/web/nginx/sbin/cut_nginx_log.sh
vi /web/nginx/sbin/cut_nginx_log.sh

输入以下内容:

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

# The Nginx logs path
logs_path="/blog/logs/"

mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path}eric_access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/eric_access_$(date -d "yesterday" +"%Y%m%d").log
mv ${logs_path}rainbow_access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/rainbow_access_$(date -d "yesterday" +"%Y%m%d").log
mv ${logs_path}default_access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/default_access_$(date -d "yesterday" +"%Y%m%d").log
kill -USR1 `cat /web/nginx/nginx.pid`

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

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

七、结束语
至此,整个 Nginx0.8.x+PHP5.2.14+Mysql5.5.3在小内存VPS服务器上的安装配置与优化 的全部过程就完成了。

需要注意的有:
1、本文中的虚拟主机部分和日志切割脚本部分的配置,仅供大家参考,因为我的VPS并非自己一人独享,所以在实际配置的时候大家要换成自己的域名和名称信息。

2、另外,如果你不是在VPS上安装,那么就请不要参考这篇文章,因为这篇文章中的配置优化都是为了占用更少的系统资源,以适应在128M或256M的环境下能够良好的运行。

3、如果你是想搭建一个性能卓越的Nginx服务器,那么还请参考上面张宴的第二篇文章,因为这篇文章的配置才是针对高并发高访问量环境的。即 http://blog.s135.com/nginx_php_v6/

, , , ,

  1. #1 by Mr.N on 2011/06/08 - 17:37

    这段代码很有问题的,参数前面的双横杠“--” 变成了 单横杠 “–” ,可能是wordpress自动替换的。我偷懒直接copy了笔者的代码,mysql永远都启动不起来。搞了一晚上..

    • #2 by mcsrainbow on 2011/06/09 - 10:07

      我看到了,确实有这个问题,双横杠变成了稍长一点的单横杠。我马上处理一下。

  2. #3 by mcsrainbow on 2011/06/09 - 10:43

    问题已经得到解决:
    编辑wp-includes/default-filters.php文件
    将有wptexturize的行注解掉

    加点内容方便其他人搜索:Wordpress 双横杠 变 单横杠 双横线 单横线

(will not be published)
*