springboot nginx动静分离


springboot nginx动静分离

                    

应用:静态资源从nginx获取,动态资源从后端获取,减轻后端服务压力

                            

                           

********************

示例

                    

*************

config 层

             

WebConfig

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
    }
}

                          

*************

前端页面

             

index.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="http://192.168.57.2:8000/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(function (){
            $("#btn").click(function (){
                $("#info").html("jquery 加载成功")
            })
        })
    </script>
</head>
<body>
<div align="center">
    <span style="color: coral">hello</span><br>
    <img src="http://192.168.57.2:8000/ymhd.jpg"/><br>

    <div id="info"></div>
    <button id="btn">点击一下</button>
</div>
</body>
</html>

                           

*************

nginx 配置

                

default.conf

server {
    listen       8000;
    server_name  localhost;

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

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://192.168.57.3:8080;
    }

    #error_page  404              /404.html;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location ~ .*\.js$ {
        root /usr/share/nginx/js;
    }

    location ~ .*\.css$ {
        root /usr/share/nginx/css;
    }

    location ~ .*\.(jpg|jpeg|bmp|png|ico)$ {
        root /usr/share/nginx/img;
    }

}

                      

*************

应用部署

                               

docker run -it -d --net fixed3 --ip 192.168.57.2 \
-v /usr/nginx/test2/default.conf:/etc/nginx/conf.d/default.conf \
-v /usr/nginx/test2/js:/usr/share/nginx/js \
-v /usr/nginx/test2/img:/usr/share/nginx/img \
--name nginx nginx

docker run -it -d --net fixed3 --ip 192.168.57.3 --name hello hello

                     

                               

********************

使用测试

               

192.168.57.2:8000/index

                          

                 

点击按钮

                          ​​​​​​​

                        

                           

Guess you like

Origin blog.csdn.net/weixin_43931625/article/details/120678660