Nginx (”engine x”) 是一个高性能的 HTTP 和反向代理服务器,由于它的高性能和稳定性,国内越来越多的网站已经开始使用 Nginx 作为 Web 服务器。以下是笔者最近一次的的安装配置笔记。
系统版本:CentOS release 5.3 (Final),安装之前,先确定服务器是否可以连通网络,否则wget、yum等网络命令均无法使用。
编辑/etc/resolv.conf
vim /etc/resolv.conf
在尾部加入下面的内容(*处填写你的DNS地址),重启就好了。
例如北京地区的DNS为:202.106.0.20 和 211.161.46.84
以下是服务器安装的各个软件的安装版本:
nginx-0.7.67:nginx最新稳定版本
mysql-5.1.49:MySQL 5.1系列最新版本
php-5.2.14:PHP5.2系列最新版本
php-5.2.14-fpm-0.5.14:以FastCGI模式编译安装PHP5.2.14时需要用到的补丁
libiconv-1.13:编译安装PHP 5.2.14所需的支持库
libmcrypt-2.5.8:编译安装PHP 5.2.14所需的支持库
mcrypt-2.6.8:编译安装PHP 5.2.14所需的支持库
memcache-2.2.5:高性能的分布式内存缓存服务器
mhash-0.9.9.9:编译安装PHP 5.2.14所需的支持库
pcre-8.01:安装Nginx所需的pcre库
eaccelerator-0.9.6:eAccelerator可以加速PHP
PDO_MYSQL-1.0.2:mysql pdo支持
ImageMagick:ImageMagick库
imagick-2.3.0:imagick库
以上版本均为截止2010.7.30日的官方最新稳定版本,可用在ssh中直接使用wget命令从官网获得:
wget http://php-fpm.org/downloads/php-5.2.14-fpm-0.5.14.diff.gz
wget http://cn2.php.net/get/php-5.2.14.tar.gz/from/cn.php.net/mirror
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.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.01.tar.gz
wget http://bart.eaccelerator.net/source/0.9.6/eaccelerator-0.9.6.tar.bz2
wget http://pecl.php.net/get/PDO_MYSQL-1.0.2.tgz
wget http://www.plhwin.com/download/webserver/ImageMagick.tar.gz
wget http://pecl.php.net/get/imagick-2.3.0.tgz
以上所有软件笔者习惯于wget到“/usr/local/src”目录中,以备后面的安装。
以下是笔者习惯的各个目录位置:
在开始安装前,强烈建议更换掉centos系统的开源软件镜像源为网易的开源软件镜像站点,这样使用yum命令安装软件时候可以获得最大的下载速度。
替换过程:
cd /etc/yum.repos.d/ mv CentOS-Base.repo CentOS-Base.repo.bak vim CentOS-Base.repo
在 vim 编辑器中填写以下内容并保存:
[base]
name=CentOS-$releasever – Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
#released updates
[updates]
name=CentOS-$releasever – Updates
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
#packages used/produced in the build but not released
[addons]
name=CentOS-$releasever – Addons
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=addons
#baseurl=http://mirror.centos.org/centos/$releasever/addons/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/addons/$basearch/
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
#additional packages that may be useful
[extras]
name=CentOS-$releasever – Extras
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever – Plus
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
mkdir -p /usr/local/webserver
mkdir -p /workspace/wwwroot
fastcgi安装PHP会用到,如果有包不需要再执行yum命令进行安装
安装nginx会用到pcre库,如果有包不需要再执行yum命令进行安装
整个安装过程中,MYSQL是最慢的一个环节,所以需要有一点耐心,如果你在执行 “make install” 的时候,一直卡在”make[4]: Entering directory `/usr/local/src/mysql-5.1.49/mysql-test’”,那是因为你太心急了,等等就编译好了,呵呵,整个卡在这个的过程大概耗时20分钟。趁这个过程喝杯茶去吧。
编译安装完成后,开始配置MYSQL,具体的步骤就先不解释了,可以网上查到,只需要按照一下步骤操作即可:
cd /usr/local/webserver/mysql cp /usr/local/webserver/mysql/share/mysql/my-medium.cnf /etc/my.cnf /usr/local/webserver/mysql/bin/mysql_install_db --user=mysql chown -R root /usr/local/webserver/mysql/ chown -R root /usr/local/webserver/mysql/var/ chown -R root /usr/local/webserver/mysql/var/mysql chown -R mysql /usr/local/webserver/mysql/ chown -R mysql /usr/local/webserver/mysql/var/ chown -R mysql /usr/local/webserver/mysql/var/mysql
增加MYSQL服务为开机自动启动:
cp /usr/local/webserver/mysql/share/mysql/mysql.server /etc/rc.d/init.d/mysqld chmod 700 /etc/init.d/mysqld chkconfig --add mysqld chkconfig --level 3 mysqld on
启动MYSQL服务
service mysqld start
设置MYSQL密码为”111111″(6个1)
/usr/local/webserver/mysql/bin/mysqladmin -u root password 111111
cp /usr/local/webserver/mysql/bin/mysql /sbin/mysql cp /usr/local/webserver/mysql/bin/mysqldump /sbin/mysqldump
测试MYSQL是否正确安装:
tar zxvf libiconv-1.13.tar.gz cd libiconv-1.13/ ./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 tar zxvf mcrypt-2.6.8.tar.gz cd mcrypt-2.6.8/ /sbin/ldconfig ./configure make make install cd ../
tar zxvf memcache-2.2.5.tgz cd memcache-2.2.5/ /usr/local/webserver/php/bin/phpize ./configure --with-php-config=/usr/local/webserver/php/bin/php-config make make install cd ../ tar jxvf eaccelerator-0.9.6.tar.bz2 cd eaccelerator-0.9.6/ /usr/local/webserver/php/bin/phpize ./configure --enable-eaccelerator=shared --with-php-config=/usr/local/webserver/php/bin/php-config make make install cd ../ tar zxvf PDO_MYSQL-1.0.2.tgz cd PDO_MYSQL-1.0.2/ /usr/local/webserver/php/bin/phpize ./configure --with-php-config=/usr/local/webserver/php/bin/php-config --with-pdo-mysql=/usr/local/webserver/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/ /usr/local/webserver/php/bin/phpize ./configure --with-php-config=/usr/local/webserver/php/bin/php-config make make install cd ../
1、手工修改:查找/usr/local/webserver/php/etc/php.ini中的extension_dir = “./”
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文件类型错误解析漏洞。
2、自动修改:若嫌手工修改麻烦,可执行以下shell命令,自动完成对php.ini文件的修改:
创建 eaccelerator 缓存目录,并编辑php.ini
mkdir -p /usr/local/webserver/eaccelerator_cache vim /usr/local/webserver/php/etc/php.ini
按shift+g键跳到配置文件的最末尾,加上以下配置信息:
/usr/sbin/groupadd www /usr/sbin/useradd -g www www
假设你已经有一个 www.test.com 的域名已经指向了服务器的IP.你需要增加这个虚拟主机站点:(如果你当前暂无可用的域名,你希望使用IP直接访问到,则无需进行下面的操作。待安装完 NGINX后,在nginx.conf文件中配置即可)
mkdir -p /workspace/wwwroot/test.com chmod +w /workspace/wwwroot/test.com chown -R www:www /workspace/wwwroot/test.com
以后要添加一个新的虚拟主机,则重复运行上面的步骤即可。
在/usr/local/webserver/php/etc/目录中创建php-fpm.conf文件:
rm -f /usr/local/webserver/php/etc/php-fpm.conf vim /usr/local/webserver/php/etc/php-fpm.conf
输入以下内容(如果您安装 Nginx + PHP 用于程序调试,请将以下的0改为1,以便显示PHP错误信息,否则,Nginx 会报状态为500的空白错误页):
All relative paths in this config are relative to php’s install prefix
Pid file
/usr/local/webserver/php/logs/php-fpm.pid
Error log file
/usr/local/webserver/php/logs/php-fpm.log
Log level
error
When this amount of php processes exited with SIGSEGV or SIGBUS …
10
… 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.
1m
Time limit on waiting child’s reaction on signals from master
5s
Set to ‘no’ to debug fpm
yes
Name of pool. Used in logs and stats.
default
Address to accept fastcgi requests on.
Valid syntax is ‘ip.ad.re.ss:port’ or just ‘port’ or ‘/path/to/unix/socket’
/tmp/php-cgi.sock
Set listen(2) backlog
-1
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.
0666
Additional php.ini defines, specific to this pool of workers.
/usr/sbin/sendmail -t -i
0
Unix user of processes
www
Unix group of processes
www
Process manager settings
Sets style of controling worker process count.
Valid values are ’static’ and ‘apache-like’
static
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.
128
Settings group for ‘apache-like’ pm style
Sets the number of server processes created on startup.
Used only when ‘apache-like’ pm_style is selected
20
Sets the desired minimum number of idle server processes.
Used only when ‘apache-like’ pm_style is selected
5
Sets the desired maximum number of idle server processes.
Used only when ‘apache-like’ pm_style is selected
35
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’
0s
The timeout (in seconds) for serving of single request after which a php backtrace will be dumped to slow.log file
‘0s’ means ‘off’
0s
The log file for slow requests
logs/slow.log
Set open file desc rlimit
65535
Set max core size rlimit
0
Chroot to this directory at the start, absolute path
Chdir to this directory at the start, absolute path
Redirect workers’ stdout and stderr into main error log.
If not set, they will be redirected to /dev/null, according to FastCGI specs
yes
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
102400
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.
127.0.0.1
Pass environment variables like LD_LIBRARY_PATH
All $VARIABLEs are taken from current environment
$HOSTNAME
/usr/local/bin:/usr/bin:/bin
/tmp
/tmp
/tmp
$OSTYPE
$MACHTYPE
2
启动php-cgi进程,监听127.0.0.1的9000端口,进程数为128(如果服务器内存小于3GB,可以只开启64个进程),用户为 www:
ulimit -SHn 65535 /usr/local/webserver/php/sbin/php-fpm start
注:/usr/local/webserver/php/sbin/php-fpm还有其他参数,包括:start|stop|quit|restart|reload|logrotate,修改php.ini后不重启php-cgi,重新加载配置文件使用reload。
创建Nginx日志目录
mkdir -p /logs/nginx chmod +w /logs/nginx chown -R www:www /logs/nginx
创建Nginx配置文件:
①、在/usr/local/webserver/nginx/conf/目录中创建nginx.conf文件:
rm -f /usr/local/webserver/nginx/conf/nginx.conf vim /usr/local/webserver/nginx/conf/nginx.conf
输入以下内容:
worker_processes 8;
error_log /logs/nginx/nginx_error.log crit;
pid /usr/local/webserver/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_http_version 1.0;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
server_name_in_redirect off;
#limit_zone crawler $binary_remote_addr 10m;
server
{
listen 80;
server_name www.test.com test.com;
index index.html index.htm index.php;
root /workspace/wwwroot/test.com;
#limit_conn crawler 20;
location ~ .*\.(php|php5)?$
{
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 1h;
}
access_log off;
}
server
{
listen 80;
server_name status.test.com;
location / {
stub_status on;
access_log off;
}
}
}
②、在/usr/local/webserver/nginx/conf/目录中创建fcgi.conf文件:
vim /usr/local/webserver/nginx/conf/fcgi.conf
输入以下内容:
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;
fastcgi_param SERVER_NAME $host;
# PHP only, required if PHP was built with –enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;
启动Nginx:
ulimit -SHn 65535 /usr/local/webserver/nginx/sbin/nginx
配置开机自动启动Nginx + PHP
vim /etc/rc.local
在末尾增加以下内容:
优化Linux内核参数:
vim /etc/sysctl.conf
在末尾增加以下内容:
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、修改/usr/local/webserver/nginx/conf/nginx.conf配置文件后,请执行以下命令检查配置文件是否正确:
/usr/local/webserver/nginx/sbin/nginx -t
如果屏幕显示以下两行信息,说明配置文件正确:
2、创建 restart.sh:
vim /usr/local/webserver/nginx/restart.sh
输入以下内容,并保存:
更改权限:
chmod 777 /usr/local/webserver/nginx/restart.sh
以后修改了 nginx.conf,php-fpm.conf,fcgi.conf 3个文件中的配置参数,都只需要运行以下shell命令即可重启nginx和PHP服务:
/usr/local/webserver/nginx/restart.sh
如果要停止NGINX服务,则执行:
kill -TERM `cat /usr/local/webserver/nginx/nginx.pid`
编写每天定时切割Nginx日志的脚本
1、创建脚本/usr/local/webserver/nginx/sbin/cut_nginx_log.sh
vim /usr/local/webserver/nginx/sbin/cut_nginx_log.sh
输入以下内容:
# The Nginx logs path
logs_path=”/usr/local/webserver/nginx/logs/”
mkdir -p ${logs_path}$(date -d “yesterday” +”%Y”)/$(date -d “yesterday” +”%m”)/
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/webserver/nginx/nginx.pid`
2、设置crontab,每天凌晨00:00切割nginx访问日志:
crontab -e
输入以下内容并保存:
注:如果无法运行 crontab 命令,可能原因是现在的很多vps没有/bin/vi,导致执行crontab提示/bin/vi 出错.解决方法是安装vim并设置为默认编辑器,方法如下:
1.安装vim
yum install vim-enhanced
2.修改/etc/profile文件,加入
3.让/etc/profile文件修改后立即生效 ,可以使用如下命令:
. /etc/profile
注意: . 和 /etc/profile 有空格
4.运行crontab -e,出现编辑界面,成功。
到此为止,整个环境基本已经全部安装好,不出意外,你已经可以成功的访问到你之前创建的虚拟主机目录 “www.test.com”了,但是凡是也有意外的情况,如果做完这一切,你发现你的服务器环境还是无法解析,请仔细查找原因,笔者就碰到这样的问题。我们一步步来排查:
执行以下命令,查看端口:
netstat -ntal
如果80端口已经在工作,可能是因为防火墙规则阻挡的缘故:
1、停止防火墙:
service iptables stop
2、停止了后在看能否打开网站,如果能,那就确定是防火墙的原因了,我们需要重新配置防火墙的规则:
vim /etc/sysconfig/iptables
3、增加以下内容并保存:
4、开启防火墙
service iptables start
如果你的服务器发现访问二级目录时候NGINX无法解析,例如当访问”http://www.test.com/test”时,服务器无法解析到 test目录,而访问”http://www.test.com/test/“则一切正常时:只需在nginx.conf中添加以下一行即可:
至此,大功基本告成。但是笔者配置的这台服务器内存为3G,CPU是双核,所以各个性能参数指标的配置均是按照这个硬件的标准来设置,在实际生产环境中,以上NGINX和PHP的配置在这个硬件换件下表现良好,但是大多数的可能是一个只有几百M内存的VPS主机,或者是自己安装配置的虚拟机环境,所以各项配置参数需要不断调优。下篇我将讲述一下都有哪些配置会影响到NGINX的运行,怎么样的配置才最合理。否则NGINX就容易出现504错误或其他的一些错误。其实这一切都不能算做是NGINX的错,只要各个参数配置合理,这样的情况是完全可以避免的。