动静分离

1. 案例背景

通过Nginx实现动静分离,即通过Nginx反向代理配置规则实现让动态资源和静态资源及其他业务分别由不同的服务器解析,以解决网站性能、安全、用户体验等重要问题。

 

2. 需求分析

  • 当用户请求www.xindaichina.cn/upload/xx地址时,实现由upload上传服务器池处理请求。
  • 当用户请求www.xindaichina.cn/static/xx地址时,实现由静态服务器池处理请求
  • 对于访问其它请求,都由默认的动态服务器池处理请求
 

3. 规划

节点IP及端口地址显示结果
web01 10.0.0.8:80 http://www.xindaichina.cn/static/index.html static
web02 10.0.0.7:80 http://www.xindaichina.cn/index.html default
web03 10.0.0.9:80 http://www.xindaichina.cn/upload/index.html upload
 

4. 部署

 

4.1 upstream地址池配置

 
upstream static_server_pools {
server 10.0.0.8:80 weight=1;
}
upstream default_server_pools {
server 10.0.0.7:80 weight=1;
}
upstream upload_server_pools {
server 10.0.0.9:80 weight=1;
}
 

 

4.2 location或if语句方案

location方案,在server{}标签中添加

location /static/ {
proxy_pass http://static_pools;
include proxy.conf;
}
location / {
proxy_pass http://default_pools;
include proxy.conf;
}
location /upload/ {
proxy_pass http://upload_pools;
include proxy.conf;
}
 if语句方案
if ($request_uri ~* "^/static/(.*)$")
{
proxy_pass http://static_pools/$1;
}
if ($request_uri ~* "^/upload/(.*)$")
{
proxy_pass http://upload_pools/$1;
}
location / {
proxy_pass http://default_pools;
include proxy.conf;
}
 

4.3 Web服务器配置

在对应的web服务器中配置对应的目录和index.html文件 

web01
mkdir static
    echo "static" >static/index.html
web02
    echo "default" >index.html
web03
    mkdir upload
    echo "upload" >upload/index.html

4.4 测试

curl www.xindaichina.cn/static/index.html
curl www.xindaichina.cn/index.html
curl www.xindaichina.cn/upload/index.html

5. 根据客户端的设备来转发

 
location / {
if ($http_user_agent ~* "android")
{
proxy_pass http://android_pools; #<==这是android服务器池,需要提前定义upstream。
}
if ($http_user_agent ~* "iphone")
{
proxy_pass http://iphone_pools; #<==这是iphone服务器池,需要提前定义upstream。
}
proxy_pass http://pc_pools;
include extra/proxy.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 android_pools {
server 10.0.0.7:80 weight=1;
}
upstream iphone_pools {
server 10.0.0.7:8080 weight=1;
}
upstream pc_pools {
server 10.0.0.8:80 weight=1;
}
server {
listen 80;
server_name www.xindaichina.cn;
location / {
if ($http_user_agent ~* "android")
{
proxy_pass http://android_pools;
}
if ($http_user_agent ~* "iphone")
{
proxy_pass http://iphone_pools;
}
proxy_pass http://pc_pools;
include proxy.conf;
}
}
}

 

posted @ 2017-11-17 12:02  答&案  阅读(360)  评论(0编辑  收藏  举报