介绍
动静分离简单说就是静态资源(js、css、img)部署一个服务器,后台应用部署一个服务器。这次做法是将静态资源部署在nginx上,后台项目部署到Tomcat服务器上达到动静分离的目标。
实例
1、在C:\Windows\System32\drivers\etc文件夹hosts文件内容中添加下面2行内容:
127.0.0.1 zy.wang.com
127.0.0.1 static.wang.com
2、在本地磁盘上创建文件夹D:\static\img,并放入图片1.png
3、配置nginx.conf文件内容
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name static.wang.com;
### 静态资源访问,直接访问本地
location /static/img {
root D:/;
index index.html index.htm;
}
}
server {
listen 80;
server_name zy.wang.com;
### 动态资源访问,直接访问本地
location / {
### 反向代理
proxy_pass http://127.0.0.1:8088;
index index.html index.htm;
}
}
}
4、双击nginx.exe启动nginx服务
5、springboot项目中application.properties内容
server.port=8088
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Chongqing
server.tomcat.max-threads=0
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
6、index.html内容
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
图片: <img width="50" height="70" src="http://static.wang.com/static/img/1.png"/>
</body>
</html>
7、启动项目后输入请求地址可看到结果,动静分离架构搭建完成。