nginx实现动静分离

时间:2023-03-10 05:47:15
nginx实现动静分离

环境信息如下:

nginx实现动静分离

测试目的:

访问jpg文件的时候,会请求到192.168.1.106上面

访问其他文件会请求到192.168.1.103上面

nginx的安装详见前面的文章

nginx的配置如下

worker_processes  1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65; upstream static_pools {
server 192.168.1.106:8080;
} upstream dynamic_pools {
server 192.168.1.103:8080;
}
server {
listen 80;
location / {
root html;
index index.html index.htm;
proxy_pass http://dynamic_pools;
} location ~ .*.(gif|jpg|jpeg|png|bmp|swf|css|js)$ { //如果请求包含这些后缀,请求被转发到静态池,否则转发到动态池
proxy_pass http://static_pools;
} }
}
~

然后重新加载配置

./nginx -s reload

测试访问结果

访问jpg文件

nginx实现动静分离

因为jpg文件只在tomcat1上面有,所以可以看到静态请求被转发给了106的机器

访问其他文件

nginx实现动静分离

因为dunamic的目录只在tomcat2上面有,因此可以看到测试是成功的

有时候有可能工程没有做成动静分离,但是通过nginx的配置可以做静态的请求转发给一些服务器,动态的请求转发给另外一些服务器。