一、为何动静分离?

可以看到,我们项目的静态资源请求和动态请求都是经过Nginx反向代理后到我们后端的Tomcat服务器,然后再返回数据,如果请求量非常的大,则后端服务器Tomcat的压力也就非常大,经过测试发现,大多数请求都是静态资源的,所以,如果降静态资源放在Nginx下,不用再到Tomcat处理,那就可以大大减轻Tomcat的压力。

Nginx动静分离_静态资源
nginxlocation详解

二、实施

将我们微服务项目下的静态资源放到Nginx 服务下
Nginx动静分离_php_02

替换原来模板文件 index.html 静态资源引入的路径:

href="/index/css/swiper-3.4.2.min.css"
// 替换为下边这个
href="/static/index/css/swiper-3.4.2.min.css"

修改niginx.conf

#负载均衡
#   upstream gulimall {  
#     # server 106.55.168.234:8080 weight=3;  
#     server http://zkgood.qicp.vip;  
#     #http://zkgood.qicp.vip/
#     }   

server {
    listen       80;
    listen  [::]:80;
    server_name  zkcool.xyz;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    # location / {
    #     root   /usr/share/nginx/html;
    #     index  index.html index.htm;
    # }

    

    
     location / {
        #  proxy_set_header Host $host;
        proxy_pass  http://zkgood.qicp.vip/;
    }
       

     location /static/ {
        root   /usr/share/nginx/html;
    }
    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}


Nginx动静分离_nginx_03