Nginx 用于动静分离

2022-04-18  本文已影响0人  hemiao3000

为了显示明显的效果,准备两台独立的服务器:

3.1 Spring Boot 项目的内容和配置

SpringBoot 项目中提供动态的 thymeleaf 页面<small>( 这是动态页面,位于 template 目录下 )</small>:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8"/>
  <title>Hello</title>
  <script src="/js/jquery-1.11.3.js"></script>
  <script type="text/javascript">
    $(function() {
        $('h2').text('hello world');
    });
  </script>
</head>
<body>
<h1 th:text="${message}">Hello World</h1>
</body>
</html>

thymeleaf 页面引用并使用了 jQuery,但是我们将项目中的 static 目录整体删除。即,Spring Boot 项目中并没有 jquery-1.11.3.js 文件。

Spring Boot 项目代码:

@RequestMapping("/api/welcome-page")
public String welcome(Model model) {
    model.addAttribute("message", "http://www.baidu.com");
    return "welcome";
}

直接运行并访问该 Spring Boot 项目,毫无疑问,你看不要页面上的 hello world 。

3.2 Nginx 配置

location .*\.js$ {
    root    html/js;
    expires      30d;
}

location /api {
    proxy_pass http://81.68.200.174:8080/api;
}

Nginx 的配置主要就是两个:

  1. 拦截以 .js 作为后缀的请求,并到指定的目录下查找、返回 .js 文件。

  2. 将接收到的以 /api 开始的请求,转向到 81.68.200.174:8080

配置正确的情况下,通过 http://127.0.0.1/api/welcome-page 向 Nginx 发出请求,你看到页面,并且能够看到页面上的 hello world

上一篇 下一篇

猜你喜欢

热点阅读