时间:2021-07-01 10:21:17 帮助过:30人阅读
配置nginx作为web_Server使用
安装nginx
# mkdir /data/software -pv # cd/data/software/ # wget http://nginx.org/download/nginx-1.6.2.tar.gz 安装之前先安装一些基本的库和依赖包 # yum install gccgcc-c++ openssl-devel pcre pcre-develzlib zlib-devel 创建web用户: groupadd -r nginx useradd -r -g nginx -s /bin/false -M nginx tar zxvfnginx-1.6.2.tar.gz cd nginx-1.6.2 ./configure --prefix=/usr --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_flv_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre
备注:--with-pcre 如果出现异常,可以去掉此参数尝试
make &&make install && echo "install nginx ok"
检查配置文件:
/usr/sbin/nginx–t
使用-V参数查看编译参数:
/usr/sbin/nginx–V

启动nginx
使用以下脚本:
vim/etc/init.d/nginx
#!/bin/sh
#
# nginx - thisscript starts and stops the nginx daemon
#
# chkconfig: - 85 15
#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 functionlibrary.
./etc/rc.d/init.d/functions
# Sourcenetworking configuration.
./etc/sysconfig/network
# Check thatnetworking is up.
["$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename$nginx)
NGINX_CONF_FILE="/etc/nginx/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
make_dirs
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
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
chkconfig nginx on
service nginxstatus
service nginxstart
service nginxrestartIE访问:
安装MySQL(通用二进制包)
cd/data/software/ groupadd -r mysql useradd -g mysql -r -s /sbin/nologin -M -d /mydata/data mysql chown -R mysql:mysql /mydata/data tar zxvfmysql-5.5.40-linux2.6-x86_64.tar.gz -C /usr/local/ cd /usr/local/ ln -svmysql-5.5.40-linux2.6-x86_64/ mysql cd mysql chownmysql:mysql ./ -R ./scripts/mysql_install_db --user=mysql --datadir=/mydata/data/ cpsupport-files/my-large.cnf /etc/my.cnf
编辑my.cnf在mysqld组中添加:
datadir=/mydata/data log-error=/mydata/data/mysql-error.log cpsupport-files/mysql.server /etc/rc.d/init.d/mysqld chkconfig --add mysqld chkconfig mysqld on service mysqldstart
输出mysqld man手册的路径
vim/etc/man.config MANPATH/usr/local/mysql/man
输出头文件的路径
ln -sv/usr/local/mysql/include /usr/local/mysql
输出mysqld库文件路径
echo"/usr/loca/mysql/lib" > /etc/ld.so.conf.d/mysql.conf ldconfig -v
安装PHP
cd/data/software/ wget http://cn2.php.net/distributions/php-5.5.18.tar.gz wget http://ncu.dl.sourceforge.net/project/mcrypt/Libmcrypt/2.5.8/libmcrypt-2.5.8.tar.gz wget http://ncu.dl.sourceforge.net/project/mhash/mhash/0.9.9.9/mhash-0.9.9.9.tar.bz2 wget http://ncu.dl.sourceforge.net/project/mcrypt/MCrypt/2.6.8/mcrypt-2.6.8.tar.gz tar zxvf libmcrypt-2.5.8.tar.gz cdlibmcrypt-2.5.8 ./configure make && make install tar jxvfmhash-0.9.9.9.tar.bz2 cd mhash-0.9.9.9 ./configure make &&make install tar zxvf mcrypt-2.6.8.tar.gz cd mcrypt-2.6.8 echo"/usr/local/lib" >> /etc/ld.so.conf && ldconfig -v ./configure vim configure 19744 # $RM "$cfgfile"
注释掉此行
make &&make install tar zxvfphp-5.5.18.tar.gz cd php-5.5.18 ./configure--prefix=/usr/local/php --with-mysql=/usr/local/mysql --with-openssl--enable-fpm --enable-sockets --enable-sysvshm--with-mysqli=/usr/local/mysql/bin/mysql_config --enable-mbstring--with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib-dir--with-libxml-dir=/usr --enable-xml --with-mhash --with-mcrypt--with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2--with-curl make &&make install cpphp.ini-production /etc/php.ini cp sapi/fpm/init.d.php-fpm /etc/rc.d/init.d/php-fpm chmod +x /etc/rc.d/init.d/php-fpm chkconfig --add php-fpm chkconfig php-fpm on cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf vim /usr/local/php/etc/php-fpm.conf
配置fpm的相关选项为你所需要的值,并启用pid文件(如下最后一行):
pm.max_children =150 pm.start_servers= 8 pm.min_spare_servers= 5 pm.max_spare_servers= 10 pid =/usr/local/php/var/run/php-fpm.pid(这个参数可以不用) service php-fpmstart lsof -i :9000
整个PHP5和nginx
Nginx vim/etc/nginx/nginx.conf
启用以下选项:
location ~ \.php${
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}并在所支持的主页面格式中添加php格式的主页,类似如下:
location / {
root html;
index index.phpindex.html index.htm;
}
创建测试页面:
# mkdir -pv/website/data
# cat >>/website/data/index.php <<EOF
> <?
> phpinfo();
> ?>
> EOF
Nginx.conf修改
location / {
root /website/data;
index index.php index.html index.htm;
}备注:这里遇到以下问题:
问题1:
52055#0: *1 FastCGI sent in stderr: "Primary script unknown" whilereading response header from upstream
将:
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
改为:
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
nginx识别不到/scripts路径,所以phpinfou验证信息无法正成通过。改成如上就是:$document_root就是针对/website/data目录下的php文件进行解析。
问题2:
一切正常之后发现phpininfo的页面为空白页
修改vim /etc/php.ini
short_open_tag =On
访问一切正常:

安装xcache,为PHP加速
cd/data/software/ wget http://xcache.lighttpd.net/pub/Releases/3.2.0/xcache-3.2.0.tar.gz tar zxvfxcache-3.2.0.tar.gz cd xcache-3.2.0 /usr/local/php/bin/phpize ./configure --enable-xcache--with-php-config=/usr/local/php/bin/php-config make &&make install mkdir -p/etc/php.d cp xcache.ini /etc/php.d/ vim /etc/php.d/xcache.ini extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20121212/xcache.so
指定具体的路径
service php-fpmrestart

Nginx虚拟主机的配置:
server {
listen 8080;
server_name localhost;
location /bbs {
root /website;
index index.html index.htmindex.php;
}
error_page 404 /404.html;
location = /404.html {
root /website/bbs;
}
}这里定义了一个虚拟主机,访问:
http://xxx.xxx.xxx.xxx:8080/bbs,实际访问的是:
http://xxx.xxx.xxx.xxx:8080/website/bbs目录
404错误页面重定向,可以隐藏版本信息,正常页面如下:
需要在HTTP区域开启:
fastcgi_intercept_errors on; 选项
然后在server中配置好:
error_page 404 /404.html;
location =/404.html {
root /website/bbs;
}
error_page 404 /404.html;
error_page 502 503 504 /50x.html;
error_page 403 http://xxx.xxx.xxx.xxx/forbidden.html;
# error_page 404 =@fetch;
location =/404.html {
root /website/bbs;
}
Upstream 模块
Upstream backup {
Server www.xxx.com weight=5;
Server www.xxx.com :8080
Server www.xxx.com down; #所有服务器挂了之后,会把请求交给此服务器
Ip_hash; #开启回话保持机制
}这里nginx支持三种会话机制:
Round-robin
Ip_hash
Least_conn
配置nginx做反向代理服务器
这里需要两台web node1 node2
配置nginx配置文件:
HTTP区域定义:
upstream webserver {
server 172.16.100.101:80 weight=1;
server 172.16.100.102:80 weight=1;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://webserver;
}
}# nginx –t&& service nginx restart


实现负载均衡
URL重写
如下:
Server {
Listen 8080;
Server_name localhost;
Location / {
Root html;
Index index.html;
Rewrite^/bbs/(.*)$ http://172.16.100.101/form/$1;
}
Error_page 404/404.html;
Localtion =/404.html {
Root html;
}
}确保后端可以正常访问:
IE访问:
http://172.16.100.128:8080/bbs/


server {
listen 8080;
server_name localhost;
location / {
root html;
index index.html index.htmindex.php;
rewrite^/bbs/(.*)$ /forum/$1;
}
}访问http://172.16.100.128:8080/bbs/ 跳转到http://172.16.100.128:8080/forum
Bbs目录不存在,这里是实现的是本机跳转。
Last :本次重写完成,重启协下一轮检查
Break:本次重写结束后,直接后续操作
常用指令使用:
alias 指令:
Location /bbs/ {
alias /website/bbs/;
index index.html index.htm;
}访问http://xxx.xxx.xxx.xxx/bbs/index.html重定向到
http://xxx.xxx.xxx.xxx/website/bbs/index.html;
Location指令:
Location /bbs/ {
Root /website/;
index index.html index.htm;
}访问http://xxx.xxx.xxx.xxx/bbs/ 实际访问是
http://xxx.xxx.xxx.xxx/website/bbs;
注意两者的区别
HTTP access 模块:
Nginx缓存机制:
nginx 缓存:
cache:共享内存,存储键和缓存对象元数据
磁盘空间,存储数据
proxy_cache_path: 不能定义在server{}中
缓存目录,子目录级别
proxy_cache_path/nginx/cache/first level=1:2:1 keys_zone=first:20m max_size=1G; cache_manager:LRU
配置如下:
HTTP区域配置:
http {
proxy_cache_path/nginx/cache/first levels=1:2:1 keys_zone=first:20m max_size=1g;
}
Server {
add_header X-Cache "$upstream_cache_status from$server_addr";
location / {
proxy_pass http://webserver;
proxy_set_header Host $host;
proxy_set_header X-Real-IP$remote_addr;
proxy_cache first;
proxy_cache_valid 200 10m
}
}

另外三个常用的缓存:
Open_log_cache:日志缓存
Open_file_cache:
Fastcgi_cache:
压缩功能:
gzip on; gzip_min_lenght 1000; gzip_proxied expired no-cache no-storeprivate auth; gzip_types text/plain application/xml;
nginx 实现动静分离
upstream phpsrvs{
server 172.16.100.101:80 weight=1;
server 172.16.100.102:80 weight=1;
}
Upstream imgsrvs{
Server 172.16.100.103:80 weight=1;
Server 172.16.100.103:80 weight=1;
}
http {
server {
location / {
root/web/htdocs;
index index.phpindex.html;
}
Location ~*\.php${
Fastcgi_passhttp://phpsrvs;
}
Location ~*”\.(jpg|jpeg|jif|png)$” {
Proxy_passhttp://imgsrvs;
}
}
}
安装memcached
cd/data/software/ wget https://cloud.github.com/downloads/libevent/libevent/libevent-1.4.14b-stable.tar.gz wget http://memcached.org/files/memcached-1.4.21.tar.gz tar zxvflibevent-1.4.14b-stable.tar.gz cd libevent-1.4.14b-stable ./configure --prefix=/usr/local/libevent make && make install tar zxvfmemcached-1.4.21.tar.gz cd memcached-1.4.21 ./configure --enable-sasl--prefix=/usr/local/memcached --with-libevent=/usr/local/libevent make && make install
memcached的常用选项说明
-l<ip_addr>:指定进程监听的地址;
-d: 以服务模式运行;
-u<username>:以指定的用户身份运行memcached进程;
-m <num>:用于缓存数据的最大内存空间,单位为MB,默认为64MB;
-c <num>:最大支持的并发连接数,默认为1024;
-p <num>: 指定监听的TCP端口,默认为11211;
-U <num>:指定监听的UDP端口,默认为11211,0表示关闭UDP端口;
-t<threads>:用于处理入站请求的最大线程数,仅在memcached编译时开启了支持线程才有效;
-f <num>:设定Slab Allocator定义预先分配内存空间大小固定的块时使用的增长因子;
-M:当内存空间不够使用时返回错误信息,而不是按LRU算法利用空间;
-n: 指定最小的slab chunk大小;单位是字节;
-S: 启用sasl进行用户认证
启动memcached
/usr/local/memcached/bin/memcached -m128 -n 20 -f 1.1 -vv -u nobody –d

Memcached操作:
telnet localhost 11211
add mykey 0 12 5
hello
get mykey
memcached启动脚本:
#!/bin/bash
#
# Init file formemcached
#
# chkconfig: - 8614
# description:Distributed memory caching daemon
#
# processname:memcached
# config:/etc/sysconfig/memcached
./etc/rc.d/init.d/functions
## Defaultvariables
PORT="11211"
USER="nobody"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""
RETVAL=0
prog="/usr/local/memcached/bin/memcached"
desc="Distributedmemory caching"
lockfile="/var/lock/subsys/memcached"
start() {
echo -n $"Starting $desc(memcached): "
daemon $prog -d -p $PORT -u $USER -c$MAXCONN -m $CACHESIZE -o "$OPTIONS"
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch$lockfile
return $RETVAL
}
stop() {
echo -n $"Shutting down $desc(memcached): "
killproc $prog
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f$lockfile
return $RETVAL
}
restart() {
stop
start
}
reload() {
echo -n $"Reloading $desc ($prog):"
killproc $prog -HUP
RETVAL=$?
echo
return $RETVAL
}
case"$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
condrestart)
[ -e $lockfile ] && restart
RETVAL=$?
;;
reload)
reload
;;
status)
status $prog
RETVAL=$?
;;
*)
echo $"Usage: $0{start|stop|restart|condrestart|status}"
RETVAL=1
esac
exit $RETVAL
chmod +x /etc/rc.d/init.d/memcached
chkconfig --add memcached
servicememcached start
动态修改使用内存:
# cat/etc/sysconfig/memcached PORT="11211" USER="nobody" MAXCONN="1024" CACHESIZE="128" OPTIONS=""
编辑/etc/init.d/memcached
# Defaultvariables PORT="11211" USER="nobody" MAXCONN="1024" CACHESIZE="64" OPTIONS="" [ -f/etc/sysconfig/memcached ] && ./etc/sysconfig/memcached
此行即可
安装memcached的php扩展
cd /data/software/ wget http://pecl.php.net/get/memcache-2.2.7.tgz wget https://codeload.github.com/junstor/memadmin/zip/master tar zxvfmemcache-2.2.7.tgz cd memcache-2.2.7 /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config --enable-memcache make && make install cat /etc/php.d/memcache.ini extension =/usr/local/php/lib/php/extensions/no-debug-non-zts-20121212/memcache.so [root@localhostmemcache-2.2.7]# service php-fpm restart

测试php使用memcached
# cat/website/data/test.php
<?php
$mem = newMemcache;
$mem->connect("127.0.0.1",11211) or die("Could notconnect");
$version =$mem->getVersion();
echo"Server‘s version: ".$version."<br/>\n";
$mem->set(‘testkey‘,‘Hello World‘, 0, 600) or die("Failed to save data at the memcachedserver");
echo "Storedata in the cache (data will expire in 600 seconds)<br/>\n";
$get_result =$mem->get(‘testkey‘);
echo"$get_result is from memcached server.";
?>[root@localhostmemcache-2.2.7]#


证明PHP程序已经可以使用memcached
Nginx 整个memcached
upstream webserver {
server 172.16.100.101:80 weight=1;
server 172.16.100.102:80 weight=1;
}
server {
listen 80;
server_name localhost;
location / {
set $memcached_key $uri;
memcached_pass 127.0.0.1:11211;
default_type text/html;
error_page 404 @fallback;
}
location @fallback {
proxy_pass http://webserver;
proxy_set_header Host $host;
proxy_set_header X-Real-IP$remote_addr;
}配置memadmin-master
unzipmemadmin-master.zip mv memadmin-master /website/data/memadmin http://172.16.100.128:8080/memadmin
配置memcached缓存mysqld数据
Memcached 和MySQL都已经安装完成
CREATE DATABASEmem_test; USE men_test; CREATE TABLE mem( id int(7) NOT NULL AUTO_INCREMENT, name char(8) DEFAULT NULL, PRIMARY KEY(id) ) ENGINE=innodb AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; INSERT INTOmem VALUES(1,‘tome‘),(2,‘james‘),(3,‘jack‘),(4,‘mary‘),(5,‘zhang‘),(6,‘lisi‘),(7,‘wangwu‘),(8,‘hello‘),(9,‘huhu‘); GRANT SELECT ON mem.* to memcache@‘%‘ IDENTIFIED BY ‘123456‘; FLUSH PRIVILEGES;
创建PHP测试页面:
# cat/website/data/memcache.php
<?php
$memcachehost =‘127.0.0.1‘;
$memcacheport =11211;
$memcachelife =60;
$memcache = newMemcache;
$memcache->connect($memcachehost,$memcacheport)or die ("Could not connect");
$query="select* from mem limit 10";
$key=md5($query);
if(!$memcache->get($key))
{
$conn=mysql_connect("127.0.0.1","memcache","12345");
mysql_select_db(memcache_test);
$result=mysql_query($query);
while($row=mysql_fetch_assoc($result))
{
$arr[]=$row;
}
$f = ‘mysql‘;
$memcache->add($key,serialize($arr),0,30);
$data = $arr ;
}
else{
$f = ‘memcache‘;
$data_mem=$memcache->get($key);
$data = unserialize($data_mem);
}
echo $f;
echo"<br>";
echo"$key";
echo"<br>";
//print_r($data);
foreach($data as$a)
{
echo "number is<b><font color=#FF0000>$a[id]</font></b>";
echo "<br>";
echo "name is<b><font color=#FF0000>$a[name]</font></b>";
echo "<br>";
}
?>[root@localhostdata]#
首次访问:
说明是从MySQL中访问的数据,再次刷新看看:
说明从memcached取到的数据,记住ID进行查询下

本文出自 “城管实习大叔” 博客,请务必保留此出处http://diudiu.blog.51cto.com/6371183/1679009
Nginx + MySQL + PHP + Xcache + Memcached
标签:nginx mysql php memcached