Nginx《二:动静分离》

210 阅读1分钟

动静分离作用

在处理静态资源(相关图片等)上tomcat并不占优势。所以动静分离利用nginx的location匹配,使静态资源自己处理,或者交由其他服务器处理,动态资源交给tomcat处理。这样带来的好处是加快了网站的访问速度,减轻后端压力,并且在后台tomcat宕机时,静态资源并不受影响。

html页面引入的静态资源路径配置

以js文件和css文件为列:

<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
  <title>Document</title>
  <link rel="stylesheet" href="/static/index/css/swiper-3.4.2.min.css">
  <link rel="stylesheet" href="/static/index/css/GL.css">
  <script src="/static/index/js/jquery-3.1.1.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="/static/index/js/swiper-3.4.2.jquery.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="/static/index/js/swiper-3.4.2.min.js"></script>
</head>

静态资源在nginx的位置

image.png 由于我的nginx是部署在docker中的,/mydata/nginx/html映射到容器的位置就是/usr/share/nginx/html

nginx关键配置如下

server {
    listen       80;
    server_name  jinlong.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;
    location /static/ {
        root /usr/share/nginx/html;
    }
    location / {
        proxy_set_header Host $host;        
        proxy_pass http://jinlong.com;
    }

    #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;
    #}
}

关于动静分离主要就这一行

    location /static/ {
        root /usr/share/nginx/html;
    }

重启nginx,idea工程代码,访问首页

image.png 可以看到关于nginx的动静分离配置已经成功!!!