一、简单配置nginx的动静分离
假设web1为静态服务器,web2为动态服务器,node2做代理
1.1 根据目录分开
web1只处理静态请求
[root@web1 ~]# mkdir -p /var/www/www/image [root@web1 ~]# yum -y install lrzsz [root@web1 ~]# cd /var/www/www/image/ [root@web1 image]# rz [root@web1 image]# ll -rw-r--r--. 1 root root 156848 Mar 13 11:31 nhrzyx.png [root@web2 ~]# vim /etc/httpd/conf/httpd.conf DocumentRoot "/var/www/www" [root@web2 ~]# systemctl restart httpd
web2只处理动态请求
[root@web2 ~]# mkdir -p /var/www/www/dynamic [root@web2 ~]# echo dynamic10 > /var/www/www/dynamic/index.html [root@web2 ~]# vim /etc/httpd/conf/httpd.conf DocumentRoot "/var/www/www" [root@web2 ~]# systemctl restart httpd
访问测试
http://172.25.254.134/image/nhrzyx.png
http://172.25.254.135/dynamic/index.html
1.2 通过请求分离
配置代理
[root@lb01 conf]# vim nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream stack_pools { server 172.25.254.134:80 weight=5; } upstream dynamic_pools { server 172.25.254.135:80 weight=5; } server { listen 80; server_name www.lbtest.com; location / { root html; index index.html index.htm; proxy_set_header Host $host; proxy_pass http://dynamic_pools; } location /image/ { proxy_set_header Host $host; proxy_pass http://stack_pools; } location /dynamic/ { proxy_set_header Host $host; proxy_pass http://dynamic_pools; } } } [root@lb01 conf]# nginx -s reload
配置hosts ,浏览器访问测试
172.25.254.131 www.lbtest.com
http://www.lbtest.com/image/nhrzyx.png
http://www.lbtest.com/dynamic/
1.3 根据扩展名分离
[root@lb01 conf]# vim nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream stack_pools { server 172.25.254.134:80 weight=5; } upstream dynamic_pools { server 172.25.254.135:80 weight=5; } server { listen 80; server_name www.lbtest.com; location / { root html; index index.html index.htm; proxy_set_header Host $host; proxy_pass http://dynamic_pools; } location ~ .*.(jpg|png|gif|css|js|swf|bmp|jsp|php|asp)$ { proxy_set_header Host $host; proxy_pass http://stack_pools; } } } [root@lb01 conf]# nginx -s reload
http://www.lbtest.com/image/nhrzyx.png
1.4 根据客户端标识进行分离
http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream stack_pools { server 172.25.254.134:80 weight=5; } upstream dynamic_pools { server 172.25.254.135:80 weight=5; } server { listen 80; server_name www.lbtest.com; location / { if ($http_user_agent ~* "MSIE") { proxy_pass http://dynamic_pools; } if ($http_user_agent ~* "firefox") { proxy_pass http://stack_pools; } } proxy_set_header Host $host; } } [root@web1 image]# echo stack_web>> /var/www/www/test.html [root@web1 image]# systemctl restart httpd [root@web2 ~]# echo dynamic_web>>/var/www/www/test.html [root@web2 ~]# systemctl restart httpd