Nginx動靜分離
動靜分離,通過中間件將動態(tài)請求和靜態(tài)請求進?分離, 分離資源, 減少不必要的請求消耗, 減少請求延時竹勉。
好處: 動靜分離后, 即使動態(tài)服務(wù)不可?, 但靜態(tài)資源不會受到影響
通過中間件將動態(tài)請求和靜態(tài)請求分離
1.Nginx動靜分離應(yīng)?案例
1.在 192.168.69.113 靜態(tài)資源
[root@Nginx conf.d]# cat access.conf
server{
listen 80;
root /soft/code;
index index.html;
location ~ .*\.(png|jpg|gif)$ {
gzip on;
root /soft/code/images;
}
}
//準(zhǔn)備?錄, 以及靜態(tài)相關(guān)圖?
[root@Nginx ~]# wget -O /soft/code/images/nginx.png http://nginx.org/nginx.png
2.在 192.168.69.113 準(zhǔn)備動態(tài)資源
[root@Nginx ~]# wget -O /soft/package/tomcat9.tar.gz \
http://mirror.bit.edu.cn/apache/tomcat/tomcat-9/v9.0.7/bin/apache-tomcat-9.0.7.tar.gz
[root@Nginx ~]# mkdir /soft/app
[root@Nginx ~]# tar xf /soft/package/tomcat9.tar.gz -C /soft/app/
[root@Nginx ~]# vim /soft/app/apache-tomcat-9.0.7/webapps/ROOT/java_test.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<HTML>
<HEAD>
<TITLE>JSP Test Page</TITLE>
</HEAD>
<BODY>
<%
Random rand = new Random();
out.println("<h1>Random number:</h1>");
out.println(rand.nextInt(99)+100);
%>
</BODY>
</HTML>
3.在 192.168.69.112 配置負載均衡代理調(diào)度, 實現(xiàn)訪問 jsp 和 png
upstream static {
server 192.168.69.113:80;
}
upstream java {
server 192.168.69.113:8080;
}
server {
listen 80;
server_name 192.168.69.112;
location / {
root /soft/code;
index index.html;
}
location ~ .*\.(png|jpg|gif)$ {
proxy_pass http://static;
include proxy_params;
}
location ~ .*\.jsp$ {
proxy_pass http://java;
include proxy_params;
}
}
測試訪問靜態(tài)資源
測試訪問動態(tài)資源
4.在 192.168.69.112 proxy 代理上編寫動靜整合 html ?件
[root@Nginx ~]# cat /soft/code/mysite.html
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>測試ajax和跨域訪問</title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://192.168.69.112/java_test.jsp",
success: function(data) {
$("#get_data").html(data)
},
error: function() {
alert("fail!!,請刷新再試!");
}
});
});
</script>
<body>
<h1>測試動靜分離</h1>
<img src="http://192.168.69.112/nginx.png">
<div id="get_data"></div>
</body>
</html>
測試動靜分離整合
當(dāng)停? Nginx 后, 強制刷新??會發(fā)現(xiàn)靜態(tài)內(nèi)容?法訪問, 動態(tài)內(nèi)容依舊運?正常