[原创]vps安装centos系统LNMP环境详细配置

2011年6月30日 | 标签: apc, iptables, linux, memcache, mysql, nginx, php, 虚拟主机

文章注释详尽,欢迎转载。

转载请注明出处:菜博  http://www.lnmpblog.com/archives/109。谢谢!

购买了一个vps,速度不错。
vps硬件配置:
cpu:E5620 4*core:256
ram:360MB
swap:360MB
HDD:15G
重新安装centos5.5 32bit 独立内核版本系统后,ssh登入。


###########################################

#                                           对用户进行修改。
###########################################

修改root密码:
passwd root
# 输入密码两次
去掉无用的用户组和用户。
cp /etc/passwd /etc/passwd.sav
cp /etc/group /etc/group.sav
for a in adm lp sync news uucp operator games gopher mailnull nscd rpc; \
do /usr/sbin/userdel $a -f; done
for a in lp news uucp games gopher users floopy nscd rpc rpcuser nfsnobody; \
do /usr/sbin/groupdel $a -f; done
升级系统并安装所需的组件
yum update -y
yum install -y at iptables mailx sendmail vixie-cron ntp ntsysv irqbalance \
patch vim-enhanced sudo flex bison automake pam-devel gcc gcc-c++ autoconf \
libjpeg libjpeg-devel libpng libpng-devel libtiff libtiff-devel libtool \
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 gd gd-devel unzip
修改用户组权限sudo权限,只允许abc用户使用sudo
chmod u+w /etc/sudoers
echo 'abc ALL=(ALL) ALL' >> /etc/sudoers
chmod u-w /etc/sudoers
修改系统时区,设置cron定期同步时间。
rm -f /etc/localtime
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
/usr/sbin/ntpdate 210.72.145.44
crontab -e
# 加入下面一行:
1 */6 * * * /usr/sbin/ntpdate 210.72.145.44 > /dev/null 2&>1
运行ntsysv精简系统启动服务,只留下atd、crond、iptables、irqbalance、network、sendmail、sshd、syslog。
ntsysv
添加用户abc并增加密码,并将abc添加到wheel组(以便sudo提权)
useradd abc
passwd abc
# 输入密码两次

/usr/sbin/usermod -G wheel xuyan
只允许wheel用户组使用su命令。
vim /etc/pam.d/su
# 去掉#auth required /lib/security/$ISA/pam_wheel.so use_uid的注释#

echo "SU_WHEEL_ONLY yes" >> /etc/login.defs
echo "root: admin@lnmpblog.com" >> /etc/aliases
newaliases
service sendmail start
如果想要发送测试邮件,使用命令
echo test | mail root
关闭ipv6
echo "alias net-pf-10 off" >> /etc/modprobe.conf
echo "alias ipv6 off" >> /etc/modprobe.conf
重启机器
init 6


###########################################

#                                           创建下载目录
###########################################

mkdir -p /data/src
cd /data/src


###########################################

#                                                安装rzsz
###########################################

安装rzsz,便于SecureCRT连接vps上传下载
cd /data/src
wget http://freeware.sgi.com/source/rzsz/rzsz-3.48.tar.gz
tar zxf rzsz-3.48.tar.gz
cd src
sed -i "s#OFLAG= -O#OFLAG= -O -DREGISTERED#g" Makefile
make posix
cp rz sz /usr/bin
export RZSZLINE=/dev/modem
cd ../
rm -rf src


###########################################

#                                 升级openssl和openssh
###########################################

# 下载相关文件
cd /data/src
wget http://ftp.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-5.8p2.tar.gz
wget http://www.openssl.org/source/openssl-1.0.0d.tar.gz
wget http://www.dnaphp.com/downloads/server/linux/30-zlib-1-2-5-tar/download -O zlib-1.2.5.tar.gz

# 升级zlib
tar -zxf zlib-1.2.5.tar.gz
cd zlib-1.2.5
./configure
make && make install
cd ../

# 升级openssl
tar zxf openssl-1.0.0d.tar.gz
cd openssl-1.0.0d
./config shared zlib
make
make install
mv /usr/bin/openssl /usr/bin/openssl.OFF
mv /usr/include/openssl /usr/include/openssl.OFF
ln -s /usr/local/ssl/bin/openssl /usr/bin/openssl
ln -s /usr/local/ssl/include/openssl /usr/include/openssl
echo "/usr/local/ssl/lib" >> /etc/ld.so.conf
/sbin/ldconfig -v
cd ../

# 升级openssh
tar zxf openssh-5.8p2.tar.gz
cd openssh-5.8p2
./configure --prefix=/usr --sysconfdir=/etc/ssh --with-pam \
--with-ssl-dir=/usr/local/ssl --with-md5-passwords --with-zlib
make
make install
cd ../
配置ssh
修改ssh端口为5678,禁止root用户通过ssh登陆,禁止空密码用户通过ssh登陆等,加强安全设置。
sed -i "s/#Port 22/Port 5678/g" /etc/ssh/sshd_config
sed -i "s/#PermitRootLogin yes/PermitRootLogin no/g" /etc/ssh/sshd_config
sed -i "s/#PermitEmptyPasswords no/PermitEmptyPasswords no/g" /etc/ssh/sshd_config
sed -i "s/UsePAM yes/UsePAM no/g" /etc/ssh/sshd_config
sed -i "s/#UseDNS yes/UseDNS no/g" /etc/ssh/sshd_config
sed -i "s/GSSAPIAuthentication yes/#GSSAPIAuthentication yes/g" /etc/ssh/sshd_config
sed -i "s/GSSAPICleanupCredentials yes/#GSSAPICleanupCredentials yes/g" /etc/ssh/sshd_config
sed -i "s/#MaxAuthTries 6/MaxAuthTries 3/g" /etc/ssh/sshd_config
sed -i "s/#X11Forwarding no/X11Forwarding no/g" /etc/ssh/sshd_config

sed -i "s/GSSAPIAuthentication yes/#GSSAPIAuthentication yes/g" /etc/ssh/ssh_config
重启ssh后,查看版本
service sshd restart
ssh -V


###########################################

#                                               防火墙设置
###########################################

增加firewall.sh脚本控制防火墙,记住,ssh上去,改防火墙,直接运行/sbin/iptables -P INPUT DROP后,你连vps都连不上了,ssh端口也被关了。
请注意你的ssh端口。我修改的是5678,请修改成自己的端口。
vim /etc/init.d/firewall.sh
添加以下代码
#!/bin/sh
#
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:~/bin
export PATH

case "$1" in
start)
 echo -n "Staring to write your Iptbales:..."
 /sbin/iptables -P INPUT DROP
 /sbin/iptables -P OUTPUT ACCEPT
 /sbin/iptables -P FORWARD DROP
 /sbin/iptables -A INPUT -i lo -j ACCEPT
 /sbin/iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT
 /sbin/iptables -A INPUT -p tcp --dport 5678 -j ACCEPT
 /sbin/iptables -A INPUT -p tcp --dport 80 -j ACCEPT
 /sbin/iptables -A INPUT -i lo -p all -j ACCEPT
 /sbin/iptables -A OUTPUT -p tcp --sport 31337 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 31340 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 31335 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 20034 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 27665 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 27444 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 9704 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 2049 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 137 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 138 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 139 -j DROP
 /etc/rc.d/init.d/iptables save
 echo "Ok"
;;
stop)
 echo -n "Cleaning your Iptables:..."
 /sbin/iptables -F
 /sbin/iptables -X
 /sbin/iptables -Z
 /sbin/iptables -P INPUT ACCEPT
 /sbin/iptables -P OUTPUT ACCEPT
 /etc/rc.d/init.d/iptables save
 echo "Ok"
;;
restart)
 echo -n "Cleaning your Iptables:..."
 /sbin/iptables -F
 /sbin/iptables -X
 /sbin/iptables -Z
 echo "Ok"
 echo -n "Staring to write your Iptbales:..."
 /sbin/iptables -P INPUT DROP
 /sbin/iptables -P OUTPUT ACCEPT
 /sbin/iptables -P FORWARD DROP
 /sbin/iptables -A INPUT -p tcp --dport 5678 -j ACCEPT
 /sbin/iptables -A INPUT -p tcp --dport 80 -j ACCEPT
 /sbin/iptables -A INPUT -i lo -p all -j ACCEPT
 /sbin/iptables -A OUTPUT -p tcp --sport 31337 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 31340 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 31335 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 20034 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 27665 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 27444 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 9704 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 2049 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 137 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 138 -j DROP
 /sbin/iptables -A OUTPUT -p tcp --sport 139 -j DROP
 /etc/rc.d/init.d/iptables save
 echo "Ok"
;;
*)
 echo "Usage: $0    {start|stop|restart}"
esac
exit 0
修改防火墙设置,并重启防火墙。
sh /etc/init.d/firewall.sh stop
sh /etc/init.d/firewall.sh start
service iptables restart


###########################################

#                                             安装mysql
###########################################

# 下载相关文件
cd /data/src
wget http://blog.s135.com/soft/linux/nginx_php/mysql/mysql-5.5.3-m3.tar.gz
# 安装mysql
tar zxf mysql-5.5.3-m3.tar.gz
cd mysql-5.5.3-m3
./configure --prefix=/usr/local/mysql/ --enable-assembler \
--with-extra-charsets=complex --enable-thread-safe-client \
--with-big-tables --with-readline --with-ssl --with-embedded-server \
--enable-local-infile --with-plugins=partition,innobase,myisammrg
make
make install

# 添加mysql用户,修改mysql目录权限
/usr/sbin/groupadd mysql
/usr/sbin/useradd -g mysql mysql -s /sbin/nologin
chown -R mysql:mysql /usr/local/mysql
cd ../
创建MySQL数据库存放目录
mkdir -p /data/mysql/data/
mkdir -p /data/mysql/binlog/
mkdir -p /data/mysql/relaylog/
chown -R mysql:mysql /data/mysql/
以mysql用户帐号的身份建立数据表,创建my.cnf配置文件:
/usr/local/mysql/bin/mysql_install_db --basedir=/usr/local/mysql \
--datadir=/data/mysql/data --user=mysql
vi /data/mysql/my.cnf
添加以下代码
[client]
default-character-set = utf8
port = 3306
socket = /tmp/mysql.sock

[mysqld]
character-set-server = utf8
user    = mysql
port    = 3306
socket = /tmp/mysql.sock
basedir = /usr/local/mysql
datadir = /data/mysql/data
log-error = /data/mysql/mysql_error.log
pid-file = /data/mysql/mysql.pid
slow-query-log  = /data/mysql/slow.log
log-bin = /data/mysql/binlog/binlog
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
default-storage-engine = MyISAM
thread_stack = 192K
tmp_table_size = 512K
max_heap_table_size = 32M
long_query_time = 1
server-id = 1
binlog_cache_size = 2M
max_binlog_cache_size = 4M
max_binlog_size = 1G
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_max_sort_file_size = 10G
myisam_repair_threads = 1
myisam_recover

[mysqldump]
quick
max_allowed_packet = 16M
创建/etc/my.cnf链接,增加/usr/local/mysql/bin/mysql环境变量,添加mysql系统启动,启动mysql。
ln -s /data/mysql/my.cnf /etc/my.cnf
ln -s /usr/local/mysql/bin/mysql /usr/bin
cp /usr/local/mysql/share/mysql/mysql.server /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld
chkconfig --add mysqld
chkconfig mysqld on
/usr/local/mysql/bin/mysqld_safe --user=mysql &
service mysqld restart
通过命令行登录管理MySQL服务器(提示输入密码时直接回车):
/usr/local/mysql/bin/mysql -u root -p -S /tmp/mysql.sock
输入以下SQL语句,删除多余用户,设置root密码(123456):
DELETE FROM mysql.user WHERE user='' or host='::1';
UPDATE mysql.user SET password=PASSWORD("123456") WHERE user='root';
flush privileges;
exit;


###########################################

#                                             php编译安装
###########################################

#安装memcached服务端(可选)

cd /data/src
wget http://monkey.org/~provos/libevent-2.0.12-stable.tar.gz
wget http://memcached.googlecode.com/files/memcached-1.4.5.tar.gz
wget http://pecl.php.net/get/memcached-1.0.2.tgz
wget http://launchpad.net/libmemcached/1.0/0.49/+download/libmemcached-0.49.tar.gz

tar zxf libevent-2.0.12-stable.tar.gz
cd libevent-2.0.12-stable
./configure --prefix=/usr/local/libevent
make && make install
cd ../
ln -s /usr/local/libevent/lib/libevent-2.0.so.5 /usr/lib/libevent-2.0.so.5
ln -s /usr/local/libevent/lib/libevent.a /usr/lib/libevent.a

tar zxf memcached-1.4.5.tar.gz
cd memcached-1.4.5
./configure --with-libevent=/usr/local/libevent/
make && make install
cd ../

tar zxf libmemcached-0.49.tar.gz
cd libmemcached-0.49
./configuremake && make install
cd ../
编写memcached启动脚本
vi /etc/init.d/memcached
添加以下内容
#!/bin/sh
#
# memcached: MemCached Daemon
#
# chkconfig: - 90 25
# description:	MemCached Daemon
#
# Source function library.
. /etc/rc.d/init.d/functions
. /etc/sysconfig/network	

start()
{
	echo -n $"Starting memcached: "
	daemon /usr/bin/memcached -u daemon -d -m 8 -c 256 -l 127.0.0.1 -p 11211 -P /tmp/memcached.pid
	echo
}

stop()
{
	echo -n $"Shutting down memcached: "
	killproc memcached
	echo
}	

[ -f /usr/bin/memcached ] || exit 0

# See how we were called.
case "$1" in
	start)
	start
	;;
	stop)
	stop
	;;
	restart|reload)
	stop
	start
	;;
	condrestart)
	stop
	start
	;;
	*)
	echo $"Usage: $0 {start|stop|restart|reload|condrestart}"
	exit 1
esac
exit 0
添加到系统启动
chkconfig --add memcached
chkconfig memcached on
编译安装PHP 5.2.17所需的其他支持库:
cd /data/src
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://downloads.sourceforge.net/mhash/mhash-0.9.9.9.tar.gz?modtime=1175740843&big_mirror=0

tar zxf libiconv-1.13.1.tar.gz
cd libiconv-1.13.1/
./configure --prefix=/usr/local
make
make install
cd ../

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

tar zxf 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 ../../

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 zxf mcrypt-2.6.8.tar.gz
cd mcrypt-2.6.8/
/sbin/ldconfig
./configure
make
make install
cd ../
编译安装php5.2.17
cd /data/src
wget http://www.php.net/get/php-5.2.17.tar.gz/from/this/mirror
wget http://php-fpm.org/downloads/php-5.2.17-fpm-0.5.14.diff.gz

tar zxf php-5.2.17.tar.gz
gzip -cd php-5.2.17-fpm-0.5.14.diff.gz | patch -d php-5.2.17 -p1
cd php-5.2.17/
./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc \
--with-mysql=/usr/local/mysql --with-mysqli=/usr/local/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 /usr/local/php/etc/php.ini
cd ../
#安装其他拓展(可选,但是建议一定要把APC装上)
cd /data/src
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.12.tar.gz
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
wget http://pecl.php.net/get/APC-3.1.9.tgz

tar zxf APC-3.1.9.tgz
cd APC-3.1.9
/usr/local/php/bin/phpize
./configure --enable-apc --enable-apc-mmap \
--with-php-config=/usr/local/php/bin/php-config --prefix=/usr/local/apc
make
make install
cd ../

tar zxf memcached-1.0.2.tgz
cd memcached-1.0.2
/usr/local/php/bin/phpize
./configure --enable-memcached --with-php-config=/usr/local/php/bin/php-config --with-zlib-dir
make
make install
cd ../

tar zxf PDO_MYSQL-1.0.2.tgz
cd PDO_MYSQL-1.0.2/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-pdo-mysql=/usr/local/mysql
make
make install
cd ../

tar zxf PDO_MYSQL-1.0.2.tgz
cd PDO_MYSQL-1.0.2/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-pdo-mysql=/usr/local/mysql
make
make install
cd ../

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

tar zxf imagick-2.3.0.tgz
cd imagick-2.3.0/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make
make install
cd ../
修改php.ini文件
sed -i 's#extension_dir = "./"#\
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"\n\
extension = "memcached.so"\nextension = "pdo_mysql.so"\nextension = "imagick.so"\n#g' \
/usr/local/php/etc/php.ini
sed -i 's#output_buffering = Off#output_buffering = On#g' /usr/local/php/etc/php.ini
sed -i 's#allow_url_fopen = Off#allow_url_fopen = On#g' /usr/local/php/etc/php.ini
sed -i 's#; always_populate_raw_post_data = On#always_populate_raw_post_data = On#g' \
/usr/local/php/etc/php.ini
sed -i 's#; cgi.fix_pathinfo=0#cgi.fix_pathinfo=0#g' /usr/local/php/etc/php.ini
sed -i 's#; cgi.fix_pathinfo=0#cgi.fix_pathinfo=0#g' /usr/local/php/etc/php.ini
在php.ini中配置APC
echo -e '[apc]\nextension="apc.so"\napc.enabled = 1\napc.cache_by_default = on\n\
apc.shm_segments = 1\napc.shm_size = 64M\napc.ttl = 7200\napc.user_ttl = 7200\n\
apc.num_files_hint = 0\napc.write_lock = On\n' >> /usr/local/php/etc/php.ini
创建www用户和web目录
/usr/sbin/groupadd www
/usr/sbin/useradd -g www www -s /sbin/nologin
mkdir -p /data/www/abc
chown -R www:www /data/www/abc
创建php-fpm配置文件:
在/usr/local/php/etc/目录中创建php-fpm.conf文件:
mv /usr/local/php/etc/php-fpm.conf /usr/local/php/etc/php-fpm.conf.bak
vi /usr/local/php/etc/php-fpm.conf
添加以下代码(<value name=”max_children”>10</value>中10为php-cgi的进程数,可以自行修改,1个进程大约消耗20MB左右内存)
<?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">/usr/local/php/logs/php-fpm.pid</value>

		Error log file
		<value name="error_log">/usr/local/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>

		<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">0</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">10</value>

			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>
增加php-fpm中chkconfig参数,添加php-fpm到系统启动项。
注:/usr/local/php/sbin/php-fpm还有其他参数,包括:start|stop|quit|restart|reload|logrotate,修改php.ini后不重启php-cgi,重新加载配置文件使用reload。
sed -i "s@#! /bin/bash@#! /bin/bash\n#chkconfig:345 61 61\n#description:php-fpm@g" \
/usr/local/php/sbin/php-fpm
ln -s /usr/local/php/sbin/php-fpm /etc/init.d/
chkconfig --add php-fpm
service php-fpm start


###########################################

#                                          nginx编译安装
###########################################

cd /data/src
wget http://sysoev.ru/nginx/nginx-1.0.4.tar.gz
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.12.tar.gz

# 安装pcre库
tar zxf pcre-8.12.tar.gz
cd pcre-8.12/
./configure
make
make install
cd ../

#安装nginx
tar zxf nginx-1.0.4.tar.gz
cd nginx-1.0.4/
./configure --user=www --group=www
make
make install
cd ../
创建日志目录
mkdir -p /data/logs
chown -R www:www /data/logs
创建Nginx配置文件
在/usr/local/nginx/conf/目录中创建vhosts目录及虚拟主机配置文件
mkdir -p /usr/local/nginx/conf/vhosts
mkdir -p /data/www/abc/blog
chown -R www:www /data/www/abc/blog
vi /usr/local/nginx/conf/vhosts/www.abc.com
加入以下内容(记得替换server_name和日志文件名abc)
server
{
	listen 80;
	server_name www.abc.tk;
	index index.html index.htm index.php;
	root  /data/www/abc/blog;

	#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 15d;
	}

	location ~ .*\.(js|css)?$
	{
		expires 1d;
	}

	log_format  abc  '$remote_addr - $remote_user [$time_local] "$request" '
		'$status $body_bytes_sent "$http_referer" '
		'"$http_user_agent" $http_x_forwarded_for';
	access_log  /data/logs/abc_access.log  abc;
}
在/usr/local/nginx/conf/目录中修改nginx.conf文件:
mv /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.bak
vi /usr/local/nginx/conf/nginx.conf
加入以下内容(worker_processes 表示开启的nginx进程数。可以自行修改,1个进程大约消耗10MB左右内存):
user  www www;

worker_processes 2;

error_log /data/logs/nginx_error.log  crit;

pid /usr/local/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;

	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;

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

	include vhosts/www.abc.com;

}
在/usr/local/nginx/conf/目录中创建fcgi.conf文件:
vi /usr/local/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;
nginx配置文件创建链接到/etc/下
ln -s /usr/local/nginx/conf /etc/nginx
编写nginx服务启动脚本
vi /etc/init.d/nginx
添加以下内容
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   345 60 60
# 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/local/nginx/sbin/nginx"
prog=$(basename $nginx) 

NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf" 

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx 

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
killall -9 nginx
} 

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
添加到系统启动
chmod +x /etc/init.d/nginx
chkconfig --add nginx
service nginx start
创建每天定时切割日志的脚本,需要切割的日志文件可自行添加,mv这一行,修改文件名即可。
vi /usr/local/sbin/cut_log.sh
输入以下内容:
#!/bin/bash
# This script run at 00:00

# The nginx logs path
logs_path="/data/logs/"

mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path}abc_access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/abc_access_$(date -d "yesterday" +"%Y%m%d").log
mv ${logs_path}nginx_error.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/nginx_error_$(date -d "yesterday" +"%Y%m%d").log
kill -USR1 `cat /usr/local/nginx/nginx.pid`
设置cron,每天凌晨00:00切割nginx访问日志
crontab -e
添加以下内容:
00 00 * * * /bin/bash  /usr/local/sbin/cut_nginx_log.sh
本文到此基本环境已经搭建好。参考了张宴老师的一些文章,也参考了其他网友的一些文章编写而成。
文章注释详尽,欢迎转载,
转载请注明出处:菜博  http://www.lnmpblog.com/archives/109。谢谢!

相关博文

  1. 2011年6月30日23:44

    没人顶我来,看在这么辛苦的份上,请吃饭啊!~

  2. 2011年6月30日23:45

    写个接口,直接转载到人人啊、新浪啊、腾讯啊,这样就方便喽

  3. 2011年6月30日23:46

    竟然没人顶!~友情帮顶的都没有,你们这帮人啊!

    • 2011年6月30日23:56

      都没有人拍砖。。我有啥办法。。。写了个这么长的文章,结果呢,访问量大增。。没人回应。。哎。

  4. 2011年7月1日17:17

    班长好 😉

  5. nickweb
    2011年7月1日19:20

    没玩过这个,来学习先

  6. xxoo
    2011年7月4日15:59

    博主辛苦了。。我来支持下啊。。写的不错~

    希望继续努力哈!!再接再厉、

  7. 2011年7月7日09:25

    直接写成shell脚本啊,方便下次使用

  8. 2011年8月18日17:31

    菜菜真厉害啊。

  9. 2011年10月9日17:24

    文章确实不错哟
    雁过留名啦
    文章相当的不错
    我的博客 http://www.learnjsj.com 欢迎光临
    加油

    • 2011年10月12日16:00

      我去看了看。。。你转过去的。。。已经面目全非,建议整理一下,欢迎转载。

  10. 真实
    2011年11月4日11:31

    好文

  11. 2014年7月22日14:28

    Aw, this was a really nice post. In thgouht I would like to put in writing like this moreover – taking time and actual effort to make a very good article… but what can I say… I procrastinate alot and under no circumstances appear to get one thing done.

WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera