一 安装nginx fastcgi 简介

   1 nginx是一个个高性能的 HTTP 和反向代理服务器,并且nginx 占用的系统资源更少
   2 xcache 是一个开源的opcode 缓存器/优化器,能提高服务器上的php 性能,xcache 通过把编译PHP后的数据缓冲到共享内存从而避免重复编译过程,能够直接使用
    缓冲区已编译的代码从而提高速度,降低服务器的负载.
   3  gperftools 是google 开发的一款优秀的LinuxC/C++ 程序的性能剖析及优化工具,他提供了将目标程序运行时所消耗的CPU 时间片进行剖析和图形输出剖析结果的功能。 
     gperftools 包含四个工具,
     分别是:TCMalloc,heap-checker,heap-profiler和cpu-profiler,TCMalloc是gperftools其中一个工具,由于优化C++写的多线程应用,与标准的glibc库的malloc 相比,
     TCMalloc 自啊内存的分配效率和速度要高, 可以在高并发的情况下很好的控制内存的使用,提供服务器的性能,降低负载.
   4 所需软件
      libunwind-1.0.1.tar.gz
      gperftools-2.0.tar.gz
      pcre-8.31.tar.gz
      nginx-1.2.5.tar.gz
      #nginx 第三方模块,开启nginx etag,默认情况下nginx 是没有该模块的
      nginx-static-etags-master.zip        
      php-5.3.19.tar.gz
      xcache-3.0.0.tar.gz
      mysql-5.0.91.tar.gz


二 libunwind 安装配置

     #tar -zxvf libunwind-1.0.1.tar.gz
     #cd libunwind-1.0.1/
     #CFLAGS=-fPIC ./configure
     #make CFLAGS=-fPIC
     #make CFLAGS=-fPIC install
     注:libunwind 库为基于64位CPU和操作系统的程序提供了基本的堆栈辗转开解功能,其中包括用于输出堆栈跟踪的API、
        用于以编程方式辗转开解堆栈的API以及支持C++异常处理机制的API


三 gperftools安装配置

  1 #tar xf   gperftools-2.0.tar.gz
    #cd   gperftools-2.0
    #./configure --enable-frame-pointers
    #make && make install
    注:如果是32位系统,可以不添加 –enable-frame-pointers,如果是64位系统,并且之前没有安装libunwind,
    那么一定要添加 –enable-frame-pointers 参数


四 pcre 安装

   #tar  xf  pcre-8.31.tar.gz
   #cd   pcre-8.31
   #./configure && make && make install


五 nginx 安装配置

  1 #tar  xf nginx-1.2.5.tar.gz
   #cd nginx-1.2.5
   # useradd -s /sbin/noloin  nginx
   #./configure --user=nginx --group=nginx --prefix=/usr/local/nginx --with-http_stub_status_module
    --with-http_ssl_module --with-google_perftools_module --with-pcre --without-mail_pop3_module 
    --without-mail_imap_module  --without-mail_smtp_module --with-http_gzip_static_module 
    --add-module=../nginx-static-etags-master
   #make && make install 
  2 nginx  配置优化
    #vim  nginx.conf
     
   user  nginx nginx ;
   worker_processes  12;
   error_log  logs/error.log  notice;
   pid        logs/nginx.pid;
   #使用google_perftools优化nginx 内存使用
   google_perftools_profiles /tmp/tcmalloc;
   worker_cpu_affinity  000000000001 000000000010 0000000000100 000000001000 000000010000 000000100000 000001000000 000010000000  000100000000 001000000000 010000000000 100000000000;
   worker_rlimit_nofile 819200;
   events {
      use  epoll;
      worker_connections  8000;
   }
 http {
   include       mime.types;
   default_type  application/octet-stream;
   #定义nginx 日志格式
   log_format  main  '$remote_addr $host $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';
   access_log  logs/access.log  main; 
  #charst
  charset UTF-8;
  server_names_hash_bucket_size 128;
  client_header_buffer_size 2k;
  large_client_header_buffers 4 128k;
  client_max_body_size 8m;
   sendfile        on;
   tcp_nopush     on;
   server_tokens off;
   #keepalive_timeout  0;
   keepalive_timeout  120;   
   #gzip  on;
   gzip  on;
   gzip_proxied  any;
   gzip_min_length   1k;
   gzip_buffers   4 16k;
   gzip_http_version 1.1;
   gzip_comp_level 3;
   gzip_types text/plain  text/css text/xml  text/javascript  application/x-javascript  charset=utf-8 application/x-java-archive application/xml image/gif image/png image/jpeg image/tiff image/x-ms-bmp application/x-shockwave-flash ;
   gzip_vary on;
  #fastcgi  set
   #设置连接后端fastcgi 超时时间
   fastcgi_connect_timeout 180;
   #设置FastCGI传送请求的超时时间
   fastcgi_send_timeout 300;
   #设置 接收FastCGI应答的超时时间
   fastcgi_read_timeout 300;
   #设置于指定读取FastCGI应答第一部分需要多大的缓冲区,这个值表示将使用1个64KB的缓冲区读取应答的第一部分(应答头)
   #   ,可以设置为fastcgi_buffers选项指定的缓冲区大小。
   fastcgi_buffer_size 128k;
   #指定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答请求。如果一个PHP脚本所产生的页面大小为256KB,
    #那么会为其分配4个64KB的缓冲区来缓存;如果页面大小大于256KB,那么大于256KB的部分会缓存到fastcgi_temp
    指定的路径中,但是这并不是好方法,因为内存中的数据处理速度要快于硬盘。
    一般这个值应该为站点中PHP脚本所产生的页面大小的中间值,如果站点大部分脚本所产生的页面大小为256KB,
    那么可以把这个值设置为“16 16k”、“4 64k”等。
   fastcgi_buffers 4  256k;
   fastcgi_busy_buffers_size 256k;
   #表示在写入缓存文件时使用多大的数据块,默认值是fastcgi_buffers的两倍
   fastcgi_temp_file_write_size 256k;
   fastcgi_intercept_errors on;
   fastcgi_ignore_client_abort on ;    
   server {
       listen       80;
       server_name  ad.frank.com.cn;
       #设置只允许访问域名,非域名返回403错误
       if ($host !~ 'ad.frank.com.cn') {
               return 403;
             }
       index index.php index.html  index.htm ;
       root /usr/local/nginx/html;
       #charset koi8-r;
        charset UTF-8;
       #设置允许访问openx 管理后台的IP 地址
        location ^~ /www/admin/ {
            allow  192.168.1.0/24;
            allow  127.0.0.1;
            deny all;       
        location ~ .*\.(php|php5)?$ {
           fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;
           include  fastcgi_params;
             }
        }
     #设置查看Xcache 状态及允许访问的IP 地址
     #set Xcache status 
       location ^~ /xcache/ {
             allow  192.168.1.0/24;
             deny all;
         
          location ~ .*\.(php|php5)?$ {
           fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;
           include  fastcgi_params;
              }
         } 
     #设置php-fpm 的状态页面及允许访问的IP 
     #set php-fpm status 
      location ^~ /(status)$ {
         
          allow 192.168.1.0/24;
          deny all;
           fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;
           include  fastcgi_params;
        }
       #access_log  logs/host.access.log  main;
       location / {
           root   /usr/local/nginx/html;
           index index.php  index.html index.htm;
       }
       #error_page  404              /404.html;
       #定义nginx 40X 错误页面
        error_page  400 = http://img.frank.com.cn/error.html;
        error_page  403 = http://img.frank.com.cn/error.html;
        error_page  404 = http://img.frank.com.cn/error.html;
      #定义 nginx 50X 错误页面
      # redirect server error pages to the static page /50x.html
        error_page  500 = http://img.frank.com.cn/error.html;
        error_page  501 = http://img.frank.com.cn/error.html;
        error_page  502 = http://img.frank.com.cn/error.html;
        error_page  503 = http://img.frank.com.cn/error.html;
       #设置吧php 代理到 php-fpm
       # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
       location ~ .*\.(php|php5)?$ {
           root    html;
           fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;   
           include  fastcgi_params;
       }
      #设置在浏览器中缓存的文件类型及时间
     location ~.*\.(jpg|js|css|png|bmp|jpeg|gif|swf)$ 
             {
        #设置防盗链,非允许的域名,返回404错误
             valid_referers none blocked *.frank.com.cn;
               if ($invalid_referer) {
                  return 404;
                 }
             root  html;
             expires 360d;
             #开启nginx etag 标签
             FileETag on;
             etag_format "%X%X";
           }
       #设置产看nginx 运行状态及允许访问的IP 地址
       #Nginx status
       location ~^/NginxStatus {
           allow 192.168.1.0/24;
           deny all;
           stub_status on;
           access_log off;
           if ( -d $request_filename){
            rewrite ^/(.*)([^/])$ http://$host/$1$2 permanent;
             }
            }
     }
  }
  3 配置nginx service启动脚本,并添加开启自动启动
     #vim  /etc/init.d/nginx
      #!/bin/sh
      #
      # nginx - this script starts and stops the nginx daemin
      #
      # chkconfig:   - 85 15
      # description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
      #               proxy and IMAP/POP3 proxy server
      # processname: nginx
      # config:      /usr/local/nginx/conf/nginx.conf
      # pidfile:     /usr/local/nginx/logs/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/local/nginx/sbin/nginx"
      prog=$(basename $nginx)
      NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
      lockfile=/var/lock/subsys/nginx
      start() {
          [ -x $nginx ] || exit 5
          [ -f $NGINX_CONF_FILE ] || exit 6
          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
          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
      #chmod 700  /etc/init.d/nginx
      #chkconfig --add nginx
      #chkconfig nginx on
   4 nginx 日志切割,并把其添加到crontable 中让其每天零点零分运行
     #cd /usr/local/nginx/sbin
     #vim   cut.nginx.log.sh
      #!/bin/bash
      #
      ##
      logs_path="/usr/local/nginx/logs/"
      if [ ! -d "$logs_path$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")" ]
        then
            mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
      fi
      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/nginx/logs/nginx.pid`
      cd  ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
      gzip -9 access_$(date -d "yesterday" +"%Y%m%d").log


六 mysql 安装配置

 1 创建mysql 用户
 #groupadd mysql
  #useradd -g mysql mysql
 
   2 编译安装mysql  #tar zxvf mysql-5.0.91.tar.gz #cd mysql-5.0.91 #./configure --prefix=/usr/local/mysql --localstatedir=/var/lib/mysql --with-plugins=innobase --with-mysqld-user=mysql --without-debug --with-big-tables --with-charset=utf8 --with-extra-charsets=all --with-pthread --enable-static --enable-thread-safe-client --with-unix-socket-path=/var/lib /mysql/mysql.sock #make&&make install 3 初始化mysql #cd /usr/local/mysql #bin/mysql_install_db –user=mysql #chown –R root:mysql . #chown –R mysql /var/lib/mysql #cp share/mysql/my-medium.cnf /etc/my.cnf #cp share/mysql/mysql.server /etc/rc.d/init.d/mysqld #chmod 755 /etc/rc.d/init.d/mysqld #chkconfig –add mysqld #chkconfig mysqld on 4 优化mysql 配置,再次省略了


七 libmcrypt 安装配置

  #tar  xf libmcrypt-2.5.8.tar.gz
  #./configure --prefix=/usr/local/libmcrypt
  #make  && make install


八 libiconv 安装配置

  #tar  xf libiconv-1.14.tar.gz
  #cd libiconv-1.14
  #./configure  --prefix=/usr/local/libiconv
  #make && make install 
 


九 php 安装配置

 1 #tar xf php-5.3.19.tar.gz
   #cd php-5.3.19
   #./configure  --prefix=/usr/local/php --with-freetype-dir --with-jpeg-dir --with-png-dir 
    --with-zlib --with-libxml-dir --enable-xml --disable-debug --enable-fpm --enable-mbstring
    --with-gd --enable-gd-native-ttf  --with-openssl --with-curl --with-curlwrappers 
    --enable-sockets --with-xmlrpc --with-mhash --with-mcrypt=/usr/local/libmcrypt/ 
    --with-mysqli=/usr/bin/mysql_config --with-mysql --enable-zend-multibyte 
    --with-iconv-dir=/usr/local/libiconv/
   #make && make install
 2 #cp   php.ini-production  /usr/local/php/lib/php.ini
 3 配置service启动php-fpm 的脚本
   #cd  sapi/fpm
   #cp  init.d.php-fpm.in   /etc/init.d/php-fpm
   #chmod 700 /etc/init.d/php-fpm
   #chkconfig --add php-fpm
   #chkconfig php-fpm on
 4 开启php 的短标签,并修改php 的时区
  #vim php.ini
    #开启php 短标签
    short_open_tag = On
    #设置php时区
    date.timezone = Asia/Hong_Kong
 5  优化php-fpm
    #cd  /usr/local/php/etc
    #cp  php-fpm.conf.default  php-fpm.conf
     修改下面的参数, 并取消注释
    #php-fpm进程文件
     pid = run/php-fpm.pid
    #设定php-fpm日志级别
     log_level =notice
    #设定php-fpm 子进程最大数目
     process.max = 300
    #设定 master process 打开的文件数目
      rlimit_files = 819200
    #指定fpm mechanism event 方式
       events.mechanism = epoll
    #指定php-fpm 运行的用户
      user = nginx 
      group = nginx
    #指定php-fpm 监听的端口
       listen = 127.0.0.1:9000
    #指定 php-fpm 监听的队列长度,默认情况下是不限制的
       listen.backlog = 2048
    #设定允许访问PHP-fpm 的IP 地址
       listen.allowed_clients = 127.0.0.1
    #指定php-fpm 的运行方式,分为static 和dynamic两种
       pm = dynamic
    # 设定最大的子进程
        pm.max_children = 300
    #设定php-fpm启动是,开启的子进程数目
        pm.start_servers = 65
    #设定php-fpm 最小空闲进程数目
        pm.min_spare_servers = 50
    #设定php-fpm,最大空闲进程数目
        pm.max_spare_servers = 80
    #设定每个子进程处理的请求数
        pm.max_requests = 1000
    #设定查看php-fpm运行状态
        pm.status_path = /status
        ping.path = /ping
        ping.response = pong
    #设定响应超时时间
        request_slowlog_timeout = 30(s)
    # 设定slow request 日志文件
        slowlog = /usr/local/php/var/log/$pool.slow.log


十 xcache 安装配置

 1 #tar  xf  xcache-3.0.0.tar.gz
   #cd  xcache-3.0.0
   #/usr/local/php/bin/phpize --clean
   #/usr/local/php/bin/phpize
   #./configure --enable-xcache --enable-xcache-optimizer 
     --with-php-config=/usr/local/php/bin/php-config
   #make && make install 
 2 在php配置文件尾部添加xcache 的配置文件,内容如下
   ;;Xcache
   ;; this is an example, it won't work unless properly configured into php.ini
   ;[xcache-common]
   ;;; non-Windows example:
   # 加载xcache.so模块路径
   extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/xcache.so
   ;;; Windows example:
   ;; extension = php_xcache.dll
   ;
   ;[xcache.admin]
   #设置xcache 管理界面(在此用户名和密码都是frank, 在此处设置的密码为md5 加密后的密码,md5为php计算出来的)
   xcache.admin.enable_auth = On
   xcache.admin.user = "frank"
   ;; set xcache.admin.pass = md5($your_password)
   ;; login use $your_password
   xcache.admin.pass = "712e5d9c46784262937bc4b2215c3beb"
  ;
  ;[xcache]
  ;; ini only settings, all the values here is default unless explained
  ;
  ;; select low level shm/allocator scheme implemenation
  xcache.shm_scheme =        "mmap"
  ;; to disable: xcache.size=0
  ;; to enable : xcache.size=64M etc (any size > 0) and your system mmap allows
  xcache.size  =        64M
  ;; set to cpu count (cat /proc/cpuinfo |grep -c processor)
  xcache.count =         12
  ;; just a hash hints, you can always store count(items) > slots
  xcache.slots =                4K
  ;; ttl of the cache item, 0=forever
  xcache.ttl   =                 0
  ;; interval of gc scanning expired items, 0=no scan, other values is in seconds
  xcache.gc_interval =           0
  ;
  ;; same as aboves but for variable cache
  xcache.var_size  =            4M
  xcache.var_count =             12
  xcache.var_slots =            4K
  ;; default value for $ttl parameter of xcache_*() functions
  xcache.var_ttl   =             0
  ;; hard limit ttl that cannot be exceed by xcache_*() functions. 0=unlimited  
  xcache.var_maxttl   =          0
  xcache.var_gc_interval =     300
  ;
  ;; mode:0, const string specified by xcache.var_namespace
  ;; mode:1, $_SERVER[xcache.var_namespace]
  ;; mode:2, uid or gid (specified by xcache.var_namespace)
  ;xcache.var_namespace_mode =    0
  ;xcache.var_namespace =        "" 
  ;
  ;; N/A for /dev/zero
  ;xcache.readonly_protection = Off
  ;; for *nix, xcache.mmap_path is a file path, not directory. (auto create/overwrite)
  ;; Use something like "/tmp/xcache" instead of "/dev/*" if you want to turn on ReadonlyProtection
  ;; different process group of php won't share the same /tmp/xcache
  ;; for win32, xcache.mmap_path=anonymous map name, not file path
  xcache.mmap_path =    "/dev/zero"
  ;
  ;
  ;; leave it blank(disabled) or "/tmp/phpcore/"
  ;; make sure it's writable by php (open_basedir is not checked)
  ;xcache.coredump_directory =   ""
  ;; disable cache after crash
  ;xcache.disable_on_crash =    Off
  ;
  ;; enable experimental documented features for each release if available
  ;xcache.experimental =        Off 
  ;
  ;; per request settings. can ini_set, .htaccess etc
  xcache.cacher =               On
  xcache.stat   =               On
  ;xcache.optimizer =           Off
  ;
  ;[xcache.coverager]
  ;; enabling this feature will impact performance
  ;; enabled only if xcache.coverager == On && xcache.coveragedump_directory == "non-empty-value"
  ;
  ;; per request settings. can ini_set, .htaccess etc
  ;; enable coverage data collecting and xcache_coverager_start/stop/get/clean() functions
  ;xcache.coverager =           Off
  ;xcache.coverager_autostart =  On
  ;
  ;; set in php ini file only
  ;; make sure it's readable (open_basedir is checked) by coverage viewer script
  ;xcache.coveragedump_directory = ""
 3 重启php-fpm
  #service php-fpm stop
  #service php-fpm  start