nginx服务与Apache服务实现动静分离
根据前几期的比克介绍nginx可知,其处理静态资源请求的功能和处理并发量的能力非常强大,但是nginx遇到动态请求就“处理不过来了”,现在的网页不只是单单有静态资源还有许多动态资源,那么该怎么处理动态请求呢?我之前也有介绍过LAMP架构,其中的Apache可以处理动态资源。那么就需要nginx处理静态请求,Apache处理动态请求。在现实的生产环境中这样做叫做动静分离。
一、LAMP架构搭建
在一台服务器上搭建LAMP架构 IP地址:192.168.80.228
- 安装Apache服务
yum install httpd httpd-devel -y
#启动Apache
systemctl start httpd
- 设置防火墙规则将Apache设置到public区域。
#开启防火墙
systemctl start firewalld
#设置规则
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
#重载防火墙
firewall-cmd --reload
- 安装mariadb数据库并且设置数据库密码
yum install mariadb mariadb-server mariadb-libs mariadb-devel -y
#开启数据库
systemctl start mariadb
#设置管理员密码
Enter current password for root (enter for none): #一开始无密码回车
OK, successfully used password, moving on...
Set root password? [Y/n] y #设置新的密码
Remove anonymous users? [Y/n] n #是否移除匿名用户选择否
Disallow root login remotely? [Y/n] n #是否禁止管理员远程登录选择否
Remove test database and access to it? [Y/n] n #是否移除测试数据选择否
Reload privilege tables now? [Y/n] y #是否重载优先级列表选择是
#设置成功!!
All done! If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!
- 安装PHP和插件与数据库相连接
#安装PHP和数据库的连接
yum install php php-mysql -y
#安装PHP的各种插件
yum install pho-gd \
php-ldap \
php-odbc \
php-pear \
php-xml \
php-xmlrpc \
php-mbstring \
php-soap \
curl curl-devel php-bcmath php-snmp -y
这样一个LAMP架构就搭建成功了。
在**/var/www/html**中创建index.php网页。
可以在测试机上访问PHP动态页面了。
二、nginx服务的搭建
在另一台服务器上搭建nginx服务。IP地址:192.168.80.229
- 手动编译安装nginx
#解压安装包
echo "所有压缩包将解压到/opt/中"
tar zxvf $lj/nginx-1.12.2.tar.gz -C /opt/ &> /dev/null
################################################
#nginx安装
#安装环境
echo "安装环境。"
yum install pcre* zlib-devel gcc gcc-c++ -y
#创建程序型用户
echo "创建nginx系统用户。"
useradd -M -s /sbin/nologin nginx
cd /opt/nginx-1.12.2
#编译 安装路径、用户、组、统计模块
./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module
make && make install
#建立软连接方便系统识别命令
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin
#创建一个启动脚本
touch /etc/init.d/nginx
#!/bin/bash
# chkconfig: - 99 20
# description: Nginx Service Control Script
name="/usr/local/nginx/sbin/nginx"
case $1 in
start)
$name
;;
stop)
killall -s QUIT $name
;;
restart)
killall -s QUIT $name
$name
;;
reload)
killall -s HUP $name
;;
*)
echo "Usage: $0 {start|stop|restart|reload}"
exit 1
esac
exit 0
EOF
#添加执行权限
chmod +x /etc/init.d/nginx
#将命令导入系统
chkconfig --add nginx
nginx服务开启成功!
2. 修改nginx主配置文件
修改nginx主配置文件使之与LAMP架构关联
- 首先备份nginx的主配置文件
cp nginx.conf nginx.conf.bak
2.其中组配置文件已经写好proxy只需要去掉注释。
:59,61 s/#/ /g
57 # proxy the PHP scripts to Apache listening on 127.0.0.1:80
58 #
59 location ~ \.php$ {
60 proxy_pass http://192.168.80.228;
61 }
3.重启nginx服务。
systemctl restart nginx
4.在测试机上访问nginx服务器IP地址并且动态请求。这样就可以在nginx服务器上收到动态请求的回应了。
三、总结
在现在的生产环境中动静分离已经成为主流,其中还是需要依赖proxy功能模块去关联LAMP架构服务器。这种也叫做反向代理。