一、动静分离概述
1.动静分离:
通过中间件也就是代理服务器把静态请求和动态请求进行分离,分离资源可以减少不必要的请求消耗,减少请求延迟
静态页面:.html .htm
Nginx:对静态页面术有专攻,动态不支持
动态页面:.jsp .php
2.原理:
中间件也就Nginx代理会把动态请求转发给其他服务器,自己只处理静态请求,当然也可以把静态请求转发给后端的可以解析静态请求的web服务器 (因为Nginx默认只能处理静态页面)
二、配置Nginx的动静分离
1.环境配置
系统 | ip | 主机名 | 软件包 | 扮演角色 |
---|---|---|---|---|
Centos7.4 | 192.168.100.10 | proxy | Nginx1.12.0 | 代理服务器 |
Centos7.4 | 192.168.100.11 | nginx | Nginx1.12.0 | 静态web |
Centos7.4 | 192.168.100.12 | nginx-02 | Nginx1.12.0 | 动态web |
2.实验目的
客户端通过代理服务器可以访问动态页面和静态页面
(1)先做基础配置(略)
[root@7-10 ~]# cd /usr/local/nginx/conf/
[root@7-10 conf]# cp nginx.conf nginx.conf.bak
[root@7-10 conf]# sed -i '/#/d' nginx.conf
[root@7-10 conf]# sed -i '/^$/d' nginx.conf
[root@7-10 ~]# vim /usr/local/nginx/conf/nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream static {
server 192.168.100.11:80 weight=5;
}
upstream java {
server 192.168.100.12:80 weight=5;
}
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html;
proxy_pass http://static;
}
location ~ .*\.(jsp|gif|png|css)$ {
proxy_pass http://java;
}
}
}
[root@7-10 ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@7-10 ~]# nginx -s reload
动态web和静态web的配置
在192.168.100.11配置
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html;
}
}
}
[root@7-11 ~]# systemctl restart nginx
[root@7-11 ~]# netstat -anpt | grep nginx
[root@7-11 ~]# echo "static" > /usr/local/nginx/html/index.html
在192.168.100.12配置
[root@7-12 ~]# cd /usr/local/nginx/conf/
[root@7-12 conf]# vim /usr/local/nginx/conf/nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.jsp;
}
}
}
[root@7-12 conf]# cd /usr/local/nginx/
[root@7-12 nginx]# cd html/
[root@7-12 html]# mv index.html index.jsp
[root@7-12 html]# echo "java" > index.jsp
[root@7-12 html]# systemctl restart nginx
[root@7-12 html]# netstat -anpt | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 45583/nginx: master
使用浏览器访问进行测试
分离成功