歡迎您光臨本站 註冊首頁

LEMP構建高性能WEB伺服器(第二版)(ZT)

←手機掃碼閱讀     火星人 @ 2014-03-04 , reply:0

LEMP構建高性能WEB伺服器(第二版)(ZT)

作者:NetSeek http://bbs.linuxtone.org(IT運維專家網|集群架構|性能調優)
歡迎轉載,轉載時請務必以超鏈接形式標明文章原始出處和作者信息及本聲明.
更新時間:2008-06-23

目錄

前言:
一、系統安裝
1. 系統分區
2.系統初始化腳本(根據具體需求關閉不需要的服務)

二、編譯安裝基本環境
1. 安裝準備
2. 編譯安裝軟體包

三、編譯安裝PHP及Nginx
1.PHP(Fastcgi)編譯安裝
2.安裝Nginx

四、Nginx多虛擬主機配置及基本優化(以配置Discuz!論壇為例)
1.配置Nginx虛擬主機(防盜鏈及expires設置)
2.Nginx搭建下載站點限制併發數和速率.
3.如何實現Nginx身份驗證
4.如何實現Nginx目錄列表
5.修改Nginx的header偽裝伺服器
6.減小nginx編譯后的文件大小
7.Nginx日誌處理

五、基本安全設置策略
六、附錄及相關介紹

前言:
本文基於step by step的結構向大家介紹Nginx構建高性能WEB的全過程.並且我們在
生產伺服器上運行一個月非常穩定,所以整理出來供大家分享。希望能夠幫助
更多的初學者輕鬆構建高性能的WEB伺服器。對文中提到的相關操作有任何問題都可以
到LinuxTone論壇去交流提問,我們將第一時間為你解答,同時把網友的建議加入,及
時更新相關內容.

系統環境:
CentOS 5.1+nginx-0.6.31+php-5.2.6+memcache-2.2.3+xcache-1.2.2+mysql-5.0.51b

一、系統安裝
1. 系統分區
   /boot 100M左右
   SWAP  物理內存的2倍(如果你的物理內存大於4G以上,分配4G即可)
   /     分區15~20G
   /usr/local 20G (用於安裝軟體)
   /data 剩餘所有空間
   *具體分區請根據相關業務劃分,具體安裝本文不作介紹.

2.系統初始化腳本(根據具體需求關閉不需要的服務)
#vi init.sh
#welcome
cat << EOF
+--------------------------------------------------------------+
|         === Welcome to CentOS System init ===                |
+--------------http://www.linuxtone.org------------------------+
+--------------------------------------------------------------+
EOF

#disable ipv6
cat << EOF
+--------------------------------------------------------------+
|         === Welcome to Disable IPV6 ===                      |
+--------------------------------------------------------------+
EOF
echo "alias net-pf-10 off" >> /etc/modprobe.conf
echo "alias ipv6 off" >> /etc/modprobe.conf
/sbin/chkconfig --level 35 ip6tables off
echo "ipv6 is disabled!"

#disable selinux
sed -i '/SELINUX/s/enforcing/disabled/' /etc/selinux/config
echo "selinux is disabled,you must reboot!"

#vim
sed -i "8 s/^/alias vi='vim'/" /root/.bashrc
echo 'syntax on' > /root/.vimrc

#LANG=en
sed -i -e 's/^LANG=.*/LANG="en"/'   /etc/sysconfig/i18n

#tunoff services
#--------------------------------------------------------------+
cat << EOF
+--------------------------------------------------------------+
|         === Welcome to Tunoff services ===                   |
+--------------------------------------------------------------+
EOF
#--------------------------------------------------------------+
for i in `ls /etc/rc3.d/S*`
do
             CURSRV=`echo $i|cut -c 15-`

echo $CURSRV
case $CURSRV in
         crond | irqbalance | microcode_ctl | network | random | sendmail | sshd | syslog | local | mysqld )
     echo "Base services, Skip!"
     ;;
     *)
         echo "change $CURSRV to off"
         chkconfig --level 235 $CURSRV off
         service $CURSRV stop
     ;;
esac
done
#sh init.sh (執行上面保存的腳本,仍后重啟)


二、編譯安裝基本環境
1. 安裝準備
   1) 系統約定
    軟體源代碼包存放位置        /usr/local/src
    源碼包編譯安裝位置(prefix)        /usr/local/software_name
    腳本以及維護程序存放位置        /usr/local/sbin
    MySQL 資料庫位置        /data/mysql/data(可按情況設置)
    網站根目錄        /data/www/wwwroot(可按情況設置)
    虛擬主機日誌根目錄        /data/logs(可按情況設置)
    Nginx運行賬戶        www:www  
    in_software_name.sh  存放編譯參數腳本    習慣將所有編譯腳本存放在in_software_name.sh便於升級和更新軟體.

    創建網站賬號及相關存放目錄
    groupadd www -g 48
    useradd -u 48 -g www www
    mkdir -p /data/www/wwwroot
    mkdir -p /data/logs
    chmod +w /data/www/wwwroot
    chown -R www:www /data/www/wwwroot
2) 系統環境部署及調整
   檢查系統是否正常
   # tail -n100 /var/log/messages        (檢查有無系統級錯誤信息)
   # dmesg (檢查硬體設備是否有錯誤信息)
   # ifconfig(檢查網卡設置是否正確)
   # ping www.linuxtone.org        (檢查網路是否正常)

  3) 使用 yum 程序安裝所需開發包(以下為標準的 RPM 包名稱)
   添加國內鏡像源加速軟體安裝下載速度請參照:http://bbs.linuxtone.org/thread-158-1-1.html
   yum -y install ntp vim-enhanced gcc gcc-c++ gcc-g77 flex bison autoconf automake bzip2-devel \
   ncurses-devel libtool* zlib-devel libxml2-devel libjpeg-devel libpng-devel libtiff-devel \
   fontconfig-devel freetype-devel libXpm-devel gettext-devel  curl curl-devel pam-devel kernel
  ◆因網友說照我的方法YUM裝的時候還是有一些錯誤,這次是按最少的包裝的:)不過還是希望網友在安裝系統的  時候就把相關的開

發包裝上。

   4) 定時校正伺服器時鐘,定時與中國國家授時中心授時伺服器同步
   # crontab -e
   加入一行:
   15 3 * * * /usr/sbin/ntpdate 210.72.145.44 > /dev/null 2>&1

  5) 下載編譯相關的源碼包.
     #vi list 在list文件里填入以後下載地址列表.
http://www.libgd.org/releases/gd-2.0.35.tar.bz2
http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.12.tar.gz
http://jaist.dl.sourceforge.net/sourceforge/mcrypt/libmcrypt-2.5.8.tar.bz2
http://jaist.dl.sourceforge.net/sourceforge/mcrypt/mcrypt-2.6.7.tar.gz
http://www.openssl.org/source/openssl-0.9.8h.tar.gz
http://openbsd.md5.com.ar/pub/OpenBSD/OpenSSH/portable/openssh-5.0p1.tar.gz

ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-7.7.tar.gz
http://sysoev.ru/nginx/nginx-0.6.31.tar.gz

http://mysql.byungsoo.net/Downloads/MySQL-5.0/mysql-5.0.51b.tar.gz

http://cn2.php.net/get/php-5.2.6.tar.bz2/from/this/mirror
http://php-fpm.anight.org/downloads/head/php-5.2.6-fpm-0.5.8.diff.gz
http://pecl.php.net/get/memcache-2.2.3.tgz
http://xcache.lighttpd.net/pub/Releases/1.2.2/xcache-1.2.2.tar.gz
http://downloads.phpchina.com/zend/optimizer/3.3.3/ZendOptimizer-3.3.3-linux-glibc23-i386.tar.gz
#vi down.sh 創建下載腳本.
#!/bin/bash
for i in `cat list`
do
wget -c $i
done         
#sh down.sh 執行下載腳本即可下載相關軟體包.

2. 編譯安裝軟體包
   源碼編譯安裝所需包(Source)
   1) 升級OpenSSL及OpenSSH
      tar xvf openssl-0.9.8h.tar.gz
      cd openssl-0.9.8h
      #vi in_openssl.sh
      ./config --prefix=/usr/local/openssl
      make
      make test
      make install
      # sh in_openssl.sh
  
      #tar xvf openssh-5.0p1.tar.gz
      #cd openssh-5.0p1
      # vi in_openssh.sh
      ./configure  \
      "--prefix=/usr" \
      "--with-pam" \
      "--with-zlib" \
      "--sysconfdir=/etc/ssh" \
      "--with-ssl-dir=/usr/local/openssl" \
      "--with-md5-passwords"
      make
      make install
      # sh in_openssh.sh
禁用 SSH V1 協議:找到#Protocol 2,1改為:Protocol 2

   禁用伺服器端GSSAPI找到以下兩行,並將它們註釋:
   GSSAPIAuthentication yes
   GSSAPICleanupCredentials yes

   禁用 DNS 名稱解析
   找到:#UseDNS yeas改為:UseDNS no

   禁用客戶端 GSSAPI
   # vi /etc/ssh/ssh_config 找到:GSSAPIAuthentication yes 將這行註釋掉。
   最後,確認修改正確后重新啟動 SSH 服務
   # service sshd restart
   # ssh -v    確認 OpenSSH 以及 OpenSSL 版本正確。

   以上SSH配置可利用以下腳本自動修改:
   #vi init_ssh.sh
   #init_ssh.sh
   ssh_cf="/etc/ssh/sshd_config"
   sed -i -e '74 s/^/#/' -i -e '76 s/^/#/' $ssh_cf
   sed -i "s/#UseDNS yes/UseDNS no/" $ssh_cf
   #client
   sed -i -e '44 s/^/#/' -i -e '48 s/^/#/' $ssh_cf
   echo "ssh is init is ok.............."
#sh init_ssh.sh
  
   # /etc/init.d/sshd restart
   Stopping sshd:                                             [  OK  ]
   Starting sshd:                                             [  OK  ]
   # ssh -v
   OpenSSH_5.0p1, OpenSSL 0.9.8h 28 May 2008


   2) GD2
      # cd /usr/local/src
      # tar xvf gd-2.0.35.tar.gz
      # cd gd-2.0.35
      # vi in_gd2.sh
      aclocal
      ./configure --prefix=/usr/local/gd2
      make && make install
      # sh in_gd2.sh
3) tar xvf libmcrypt-2.5.8.tar.bz2
      cd libmcrypt-2.5.8
      #vi in_libmcrypt.sh
      ./configure --prefix=/usr/local/libmcrypt && make && make install
      #sh in.sh
4) #tar xvf libiconv-1.12.tar.gz
      #cd libiconv-1.12
      #vi in_iconv.sh
      ./configure --prefix=/usr && make && make install
#sh in_iconv.sh
   5) 編譯安裝MySQL
     
     # tar xvf mysql-5.0.51b.tar.gz
     # cd mysql-5.0.51b
     # vi in_mysql.sh
    CFLAGS="-O3" CXX=gcc CXXFLAGS="-O3 -felide-constructors \
    -fno-exceptions -fno-rtti -fomit-frame-pointer -ffixed-ebp"
    ./configure \
        "--prefix=/usr/local/mysql" \
        "--localstatedir=/data/mysql/data" \
        "--with-comment=Source" \
        "--with-server-suffix=-LinuxTone.Org" \
        "--with-mysqld-user=mysql" \
        "--without-debug" \
        "--with-big-tables" \
        "--with-charset=gbk" \
        "--with-collation=gbk_chinese_ci" \
        "--with-extra-charsets=all" \
        "--with-pthread" \
        "--enable-static" \
        "--enable-thread-safe-client" \
        "--with-client-ldflags=-all-static" \
        "--with-mysqld-ldflags=-all-static" \
        "--enable-assembler" \
        "--without-isam" \
        "--without-innodb" \
        "--without-ndb-debug"
    make && make install
    useradd mysql -d /data/mysql -s /sbin/nologin
    /usr/local/mysql/bin/mysql_install_db --user=mysql
    cd /usr/local/mysql
    chown -R root:mysql .
    chown -R mysql /data/mysql/data
    cp share/mysql/my-huge.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
    /etc/rc.d/init.d/mysqld start

    cd /usr/local/mysql/bin   
    for i in *; do ln -s /usr/local/mysql/bin/$i /usr/bin/$i; done
#sh in_mysql.sh

[ 本帖最後由 3PCman 於 2008-6-24 16:42 編輯 ]
《解決方案》

三、編譯安裝PHP及Nginx
1.PHP(Fastcgi)編譯安裝

  1)php-fpm 給PHP(Fastcgi)打補丁
    #tar xvf php-5.2.6.tar.bz2
    #gzip -cd php-5.2.6-fpm-0.5.8.diff.gz | patch -d php-5.2.6 -p1

  2)PHP(Fastcgi)安裝.
    #cd php-5.2.6
    #vi in_php5.sh
./configure \
        "--prefix=/usr/local/php-fcgi" \
        "--enable-fastcgi" \
        "--enable-fpm" \
        "--enable-discard-path" \
        "--enable-force-cgi-redirect" \
        "--with-config-file-path=/usr/local/php-fcgi/etc" \
        "--enable-zend-multibyte" \
        "--with-mysql=/usr/local/mysql" \
        "--with-libxml-dir" \
        "--with-iconv-dir=/usr/lib" \
        "--with-xmlrpc" \
        "--with-gd=/usr/local/gd2" \
        "--with-jpeg-dir" \
        "--with-png-dir" \
        "--with-bz2" \
        "--with-freetype-dir" \
        "--with-zlib-dir " \
        "--with-openssl=/usr/local/openssl" \
        "--with-mcrypt=/usr/local/libmcrypt" \
        "--enable-sysvsem" \
        "--enable-inline-optimization" \
        "--enable-soap" \
        "--enable-gd-native-ttf" \
        "--enable-ftp" \
        "--enable-mbstring" \
        "--enable-exif" \
        "--disable-debug" \
        "--disable-ipv6"
     make && make install
     cp php.ini-dist /usr/local/php-fcgi/etc/php.ini
#sh in_php5.sh


  4)安裝Xcache
  tar xvf xcache-1.2.2.tar.gz
  cd xcache-1.2.2
  #vi in_xcache.sh
  /usr/local/php-fcgi/bin/phpize
  ./configure --enable-xcache --enable-xcache-coverager --with-php-config=/usr/local/php-

fcgi/bin/php-config \
   --enable-inline-optimization --disable-debug
  make && make install
#sh in_xcache.sh
  
  #vi /usr/local/php-fcgi/etc/php.ini  #編輯php.ini在其內容最後加入如下內容:

zend_extension      = /usr/local/php-fcgi/lib/php/extensions/no-debug-non-zts-20060613/xcache.so


xcache.admin.user   = "admin"
;如何生成md5密碼: echo -n "password"| md5sum
xcache.admin.pass   = "035d849226a8a10be1a5e0fec1f0f3ce"  #密碼為52netseek


; Change xcache.size to tune the size of the opcode cache
xcache.size         = 24M
xcache.shm_scheme   = "mmap"
xcache.count        = 4
xcache.slots        = 8K
xcache.ttl          = 0
xcache.gc_interval  = 0

; Change xcache.var_size to adjust the size of variable cache
xcache.var_size     = 8M
xcache.var_count    = 1
xcache.var_slots    = 8K
xcache.var_ttl      = 0
xcache.var_maxttl   = 0
xcache.var_gc_interval =     300
xcache.test         = Off
xcache.readonly_protection = On
xcache.mmap_path    = "/dev/zero"
xcache.coredump_directory =   ""
xcache.cacher       = On
xcache.stat         = On
xcache.optimizer    = Off


xcache.coverager    = On
xcache.coveragedump_directory = ""
4)安裝Memcache
  cd memcache-2.2.3
#vi in_memcache.sh
  /usr/local/php-fcgi/bin/phpize
./configure --with-php-config=/usr/local/php-fcgi/bin/php-config
make && make install
#sh in_memcache.sh

  5) PHP初始化腳本
# cat init_fcgi.sh
#!/bin/bash
#php-fastcgi.php
fcgi_cf="/usr/local/php-fcgi/etc/php.ini"
sed -i '205 s#;open_basedir =#open_basedir = /data/www/wwwroot:/tmp#g' $fcgi_cf
sed -i '210 s#disable_functions =#disable_functions =

phpinfo,passthru,exec,system,chroot,scandir,chgrp,chown,shell_exec,proc_open,proc_get_status,ini_

alter,ini_alter,ini_restore,

dl,pfsockopen,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server#g' $fcgi_cf
sed -i '/expose_php/s/On/Off/' $fcgi_cf
sed -i '/display_errors/s/On/Off/' $fcgi_cf
sed -i 's#extension_dir = "./"#extension_dir = "/usr/local/php-fcgi/lib/php/extensions/no-debug-

non-zts-20060613/"\nextension

= "memcache.so"\n#' $fcgi_cf
6)ZendOptimizer-3.3.3-linux-glibc23-i386 (解壓後進入目錄./install,安提示選擇相關的目錄及

配置文件存放目錄即可)

2.安裝Nginx
1)Nginx編譯安裝

cd nginx-0.6.31
#vi in_nginx.sh
./configure --user=www --group=www --prefix=/usr/local/nginx/ --with-http_stub_status_module --

with-

openssl=/usr/local/openssl
make && make install
sh in_nginx.sh

2)初始化Nginx相關配置
  #mkdir /usr/local/nginx/conf/vhosts  創建存放虛擬主機配置文件目錄
  #cd /usr/local/nginx/conf
  #mv nginx.conf nginx.conf_back 將原配置文件備份供以後參考.
  #vi nginx.conf 重新創建nginx主配置文件
user  www www;

worker_processes 8;

pid /var/run/nginx.pid;
# [ debug | info | notice | warn | error | crit ]
#error_log  /var/log/nginx.error_log  info;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 51200;

events
{
       use epoll;

       #maxclient = worker_processes * worker_connections / cpu_number
       worker_connections 51200;
}

http
{
       include       mime.types;
       default_type  application/octet-stream;
       charset  gb2312;
       server_names_hash_bucket_size 128;

       log_format  main  '$remote_addr - $remote_user [$time_local] $request '
                         '"$status" $body_bytes_sent "$http_referer" '
                         '"$http_user_agent" "$http_x_forwarded_for"';

       #access_log  /data/www/logs/access.log  main;
       access_log  /dev/null;

       sendfile on;
       tcp_nopush     on;
       keepalive_timeout 60;
       tcp_nodelay on;

       fastcgi_connect_timeout 60;
       fastcgi_send_timeout 180;
       fastcgi_read_timeout 180;
       fastcgi_buffer_size 128k;
       fastcgi_buffers 4 128k;
       fastcgi_busy_buffers_size 128k;
       fastcgi_temp_file_write_size 128k;
       fastcgi_intercept_errors on;

       gzip on;
       gzip_min_length  1k;
       gzip_buffers     4 8k;
       gzip_http_version 1.1;
       gzip_types       text/plain application/x-javascript text/css text/html application/xml;

       #
       client_max_body_size       10m;
       client_body_buffer_size    256k;
       #
       #proxy_temp_path            /dev/shm/proxy_temp;
       fastcgi_temp_path          /dev/shm/fastcgi_temp;
       client_body_temp_path      /dev/shm/client_body_temp;


       # The following includes are specified for virtual hosts
       include          vhosts/bbs.linxutone.org.conf;
       include          vhosts/down.redocn.com.conf;
       include          vhosts/count.linuxtone.org.conf;
}

#vi /enable_php5.conf Nginx支持PHP配置文件.
fastcgi_pass  127.0.0.1:8085;
fastcgi_index index.php;

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;
3)配置修改php-fpm腳本
配置php-fpm腳本:
cd /usr/local/php-fcgi/etc/
vi php-fpm.conf  修改如下內容:(進入vi編輯器,輸入:set nu 顯示行號.)

41                         <value name="listen_address">127.0.0.1:8085</value>
62                         Unix user of processes
63                         <value name="user">www</value>
65                         Unix group of processes
66                         <value name="group">www</value>
79                                 <value name="max_children">128</value>
80
81                                 Settings group for 'apache-like' pm style
82                                 <value name="apache_like">
83
84                                         Sets the number of server processes created on

startup.
85                                         Used only when 'apache-like' pm_style is selected
86                                         <value name="StartServers">20</value>
87
88                                         Sets the desired minimum number of idle server

processes.
89                                         Used only when 'apache-like' pm_style is selected

90                                         <value name="MinSpareServers">5</value>
91
92                                         Sets the desired maximum number of idle server

processes.
93                                         Used only when 'apache-like' pm_style is selected
94                                         <value name="MaxSpareServers">250</value>
104                         Set open file desc rlimit
105                         <value name="rlimit_files">51200</value>
106
107                         Set max core size rlimit
108                         <value name="rlimit_core">0</value>
109
110                         Chroot to this directory at the start
111                         <value name="chroot"></value>
112
113                         Chdir to this directory at the start
114                         <value name="chdir"></value>
115
116                         Redirect workers' stdout and stderr into main error log.
117                         If not set, they will be redirected to /dev/null, according to

FastCGI specs
118                         <value name="catch_workers_output">yes</value>
119
120                         How much requests each process should execute before respawn.
121                         Useful to work around memory leaks in 3rd party libraries.
122                         For endless request processing please specify 0
123                         Equivalent to PHP_FCGI_MAX_REQUESTS
124                         <value name="max_requests">51200</value>


4) Nginx+PHP(fastcgi)啟動腳本參考:http://bbs.linuxtone.org/thread-372-1-2.html
《解決方案》

四、Nginx多虛擬主機配置及基本優化(以配置Discuz!論壇為例)

1.配置Nginx虛擬主機(防盜鏈及expires設置)
#vi /usr/local/nginx/conf/vhosts/bbs.linuxtone.org.conf
server
       {
               listen       80;
               server_name  bbs.linuxtone.org www.linuxtone.org;
               index index.html index.php index.htm;
               root  /data/www/wwwroot/lt/bbs;
               #access_log /var/log/nginx/access_bbs.redocn.com.log  combined;
               location / {
               if (!-e $request_filename) {
                         rewrite ^/archiver/((fid|tid)-[\w\-]+\.html)$   /archiver/index.php?$1

last;
                         rewrite ^/forum-(+)-(+)\.html$   /forumdisplay.php?

fid=$1&page=$2 last;
                         rewrite ^/thread-(+)-(+)-(+)\.html$  /viewthread.php?

tid=$1&extra=page%3D$3&page=$2

last;
                         rewrite ^/space-(username|uid)-(.+)\.html$   /space.php?$1=$2 last;
                         rewrite ^/tag-(.+)\.html$ /tag.php?name=$1 last;
                         break;
                                          }

                }

               #Preventing hot linking of images and other file types
               location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {
                       valid_referers none blocked server_names *.linuxtone.org http://localhost;
               if ($invalid_referer) {
               rewrite   ^/   http://bbs.linuxtone.org/images/default/logo.gif;
               return   403;
                                     }
                                                               }
               # Add expires header for static content
               location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
               if (-f $request_filename) {
                  root /data/www/wwwroot/lt/bbs;
                  expires      1d;
                  break;
                  }

               }
               #support php
               location ~ .*\.php?$
               {
                       include enable_php5.conf;
               }

       }
2.Nginx搭建下載站點限制併發數和速率.
vi /usr/local/nginx/conf/vhosts/down.redocn.com.conf
limit_zone   one  $binary_remote_addr  10m;
server
       {
               listen       80;
               server_name  down.redocn.com;
               index index.html index.htm index.php;
               root   /data/www/wwwroot/down;
               error_page 404 /index.php;
               # redirect server error pages to the static page /50x.html
               error_page   500 502 503 504  /50x.html;
               location = /50x.html {
                root   html;
                  }
               #Zone limit
               location / {
                   limit_conn   one  1;
                   limit_rate  20k;
               }


               # serve static files
               location ~ ^/(images|javascript|js|css|flash|media|static)/  {
               root    /data/www/wwwroot/down;
               expires 30d;
                }
       }
3.如何實現Nginx身份驗證
實現輸入http://count.linuxtone.org/tongji 要求輸入用戶名和密碼驗證才可查看內內。配置方

法如下:
創建統計配置文件:
mkdir /usr/local/nginx/conf/htpasswd  #創建存放密碼的目錄
/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji admin

server
       {
               listen       80;
               server_name  count.linuxtone.org;
               index index.html index.php;
               root  /data/www/wwwroot/count;
               access_log /data/logs/access_count.linuxtone.org.log  combined;
               #error page
               error_page 404 http://www.linuxtone.org/error.html;
               error_page 500 502 503 504 http://www.linuxtone.org;
               #support php
               location ~ .*\.php?$
               {
                       include enable_php5.conf;
               }

               #expires static files
               location ~* \.(js|css|jpg|jpeg|gif|png)$ {
               if (-f $request_filename) {
                  access_log   off;
                  expires      1d;
                  break;
                  }
               }
              location ~ ^/(tongji)/  {
                root    /data/www/wwwroot/count;
                        auth_basic              "LT-COUNT-TongJi";
                        auth_basic_user_file  /usr/local/nginx/conf/htpasswd/tongji;
                }

      }
4.如何實現Nginx目錄列表
在相關虛擬主機配置文件加入如下設置即可,更多請參考官方wiki
location  /  {
    autoindex  on;
}
5.修改Nginx的header偽裝伺服器
cd nginx-0.6.31/src/core
#define NGINX_VERSION      "1.2"
#define NGINX_VER          "LTWS/" NGINX_VERSION
仍后重新編譯nginx即可,查看一下效果:
# curl -I http://bbs.linuxtone.org
HTTP/1.1 200 OK
Server: LTWS/1.2
Date: Mon, 23 Jun 2008 06:11:17 GMT
Content-Type: text/html; charset=gb2312
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: lt__sid=cJN2FT; expires=Mon, 30-Jun-2008 06:11:17 GMT; path=/
Set-Cookie: lt__onlineusernum=228; expires=Mon, 23-Jun-2008 06:16:17 GMT; path=/
6.減小nginx編譯后的文件大小 (Reduce file size of nginx)
默認的nginx編譯選項里居然是用debug模式(-g)的(debug模式會插入很多跟蹤和ASSERT之類),編譯以後一個

nginx有好幾兆。
去掉nginx的debug模式編譯,編譯以後只有480K(nginx-0.6.31 , gcc4)。
# du -sh nginx
480K    nginx
在auto/cc/gcc,最後幾行有:
# debug
CFLAGS="$CFLAGS -g"
註釋掉或刪掉這幾行,重新編譯即可

7.Nginx日誌處理
# crontab -l
59 23 * * * /usr/local/sbin/logcron.sh /dev/null 2>&1
# cat /usr/local/sbin/logcron.sh
#!/bin/bash
log_dir="/data/logs"
time=`date +%Y%m%d`  
/bin/mv  ${log_dir}/access_linuxtone.org.log ${log_dir}/access_count.linuxtone.org.$time.log
kill -USR1 `cat  /var/run/nginx.pid`
更多的日誌分析與處理就關注(同時歡迎你參加討論):http://bbs.linuxtone.org/forum-8-1.html


五、基本安全設置策略
  1)SSH安全策略:經常升級OpenSSH,SSH全安(修改SSH埠限制來源IP登陸,或者參考

http://bbs.linuxtone.org/thread-106-1-1.html)
  2)關掉不需要的服務可以利用上文提到的腳本;iptables 封鎖相關埠(推薦讀CU白金大哥的兩小時玩轉iptables)
  3)做好系統監控和審計相關的工作,做好系統自動化備份腳本,保證數據短時期可以恢復最近時間段,降低損失!
  4)Linux防Arp攻擊策略(http://bbs.linuxtone.org/thread-41-1-1.html)
  5)注意(還是那句老話:安全工作從細節做起!)更多的請實時關注:http://bbs.linuxtone.org/forum-21-1.html (安全專項)

六、附錄及相關介紹
1.參考文檔(對相關作者分享精神表示感謝!):
  Reduce file size of nginx:  http://bianbian.org/technology/271.html
  構建LEMP相關文章(作者:張宴): http://blog.s135.com/read.php/351.htm
  基於CentOS構建高性能的LAMP平台: http://bbs.linuxtone.org/thread-122-1-1.html
  利用Nginx替代apache實現高性能的Web環境(第一版): http://bbs.linuxtone.org/thread-7-1-1.html

[ 本帖最後由 3PCman 於 2008-6-24 16:43 編輯 ]
《解決方案》

樓主和張堰寫的都差不多,能不能加上配置內容的註釋。這樣大家才能更好的根據自己的需要配置。我舉個例子。比如:配置php-fpm腳本:
cd /usr/local/php-fcgi/etc/
vi php-fpm.conf  下面的內容。哪些數字的具體含義內容,如何優化等等。。。不是每個人的環境都和「張堰」一樣的。
《解決方案》

嗯,再加註釋就太長了,等linuxtone出HTML版,我要求他寫詳細一點。
《解決方案》

回復 #5 3PCman 的帖子

期待HTML 版。越詳細越好。:mrgreen:
《解決方案》

是好文章 就要頂!
《解決方案》

不錯的文章
《解決方案》

關閉SELinux,安全性變差
《解決方案》

我喜歡.在學習中.下來瞅瞅啊.

[火星人 ] LEMP構建高性能WEB伺服器(第二版)(ZT)已經有919次圍觀

http://coctec.com/docs/service/show-post-29195.html