前言:本博客仅作记录学习使用,部分图片出自网络,如有侵犯您的权益,请联系删除
一、什么是动静分离
为了加快网站的解析速度,可以把动态页面和静态页面由不同的服务器来解析,加快解析速度。降低原来单个服务器的压力。 在动静分离的tomcat的时候比较明显,因为tomcat解析静态很慢,其实这些原理的话都很好理解,简单来说,就是使用正则表达式匹配过滤,然后交个不同的服务器
通过location指定不同的后缀名实现不同的请求转发,也可以通过expires参数设置,使浏览器缓存文件的过期时间,从而减少与服务器之前的请求和流量
二、实验
1、环境准备
主机名 | 主机地址 | 说明 |
---|---|---|
centos | 10.0.0.2 | 静态web服务器 |
centos-2 | 10.0.0.3 | 动态web服务器 |
centos-3 | 10.0.0.4 | 代理服务器 |
2、静态web服务器配置:
2.1、配置静态文件
此处使用默认的nginx配置,只是将nginx默认首页更改充当静态资源。
# 查看nginx服务状态
[root@centos ~]# systemctl status nginx
[root@centos html]# cat /usr/share/nginx/html/index.html
My domain IP is 10.0.0.2
2.2、浏览器访问:
3、动态web服务器配置:
3.1、PHP配置动态页面
使用php编写的首页文件来充当动态资源来做示例:
(1)下载epel源与php相关软件包:
[root@centos-2 ~]# wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
[root@centos-2 ~]# yum -y install nginx php-fpm php-mysql php-mbstring
# 启动并验证
[root@centos-2 ~]# systemctl start php-fpm
[root@centos-2 ~]# netstat -tunlp | grep 9000
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 6990/php-fpm: maste
(2)nginx配置:
[root@centos-2 ~]# vim /etc/nginx/conf.d/default.conf
server {
listen 80;
server_name localhost;
location ~ \.php$ {
root /usr/share/nginx/html; #指定网站目录
fastcgi_pass 127.0.0.1:9000; #指定访问地址
fastcgi_index index.php; #指定默认文件
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #站点根目录,取决于root配置项
include fastcgi_params; #包含nginx常量定义
}
}
[root@centos-2 html]# cat /usr/share/nginx/html/index.php
<?php
phpinfo();
?>
[root@centos-2 html]# nginx -t
[root@centos-2 html]# nginx -s reload
3.2、浏览器访问:
4、代理配置
4.1、配置
[root@centos-3 ~]# cat /etc/nginx/conf.d/default.conf
upstream static {
server 10.0.0.2:80 weight=1 max_fails=1 fail_timeout=60s;
}
upstream php {
server 10.0.0.3:80 weight=1 max_fails=1 fail_timeout=60s;
}
server {
listen 80;
server_name localhost;
#动态资源加载
location ~ \.(php|jsp)$ {
proxy_pass http://php;
proxy_set_header Host $host:$server_port; # 设置代理请求的Host头部
proxy_set_header X-Real-IP $remote_addr; # 原始客户端的IP地址
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 记录请求经过的代理的IP地址,下同
}
#静态资源加载
location ~ .*\.(html|gif|jpg|png|bmp|swf|css|js)$ {
proxy_pass http://static;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
[root@centos-3 ~]# nginx -t
[root@centos-3 ~]# nginx -s reload
4.2、测试
当访问动态页面时location匹配到 .\php 结尾的文件转发到后端php服务处理请求。
当访问静态页面的时候location 匹配到 (html|jpg|png|js|css|gif|bmp|jpeg) 通过转发到静态服务器,静态服务通过location的正则匹配来处理请求。
三、相关知识
1、location
1.1、正则表达式匹配
location前缀可以使用正则表达式
前缀 | 说明 | |
---|---|---|
/ | 通用匹配 | 任何请求都会匹配到 |
= | 精准匹配 | 不是以指定模式开头 |
~ | 正则匹配 | 区分大小写 |
~* | 正则匹配 | 不区分大小写 |
^* | 非正则匹配 | 匹配以指定模式开头的location |