1. 程式人生 > 其它 >Nginx + Tomcat 有關SSI 的那些事兒

Nginx + Tomcat 有關SSI 的那些事兒

在工作中使用到SSI,對於靜態頁面由Nginx處理SSI是沒有問題。對於jsp 檔案裡面的SSI怎麼辦呢?我們不想開啟Tomcat的 SSI功能,我們希望SSI 的解析交給Nginx來完成,Tomcat 只處理應用。

下面的文章用例項說明這是可行的。

文章節選擇 《Netkiller Web 手札》 Tomcat 篇

3.2.6.5. Proxy 與 SSI

背景:nginx + tomcat 模式,nginx 開啟 SSI , Tomcat 動態頁面中輸出 SSI 標籤

		# cat  /etc/nginx/conf.d/www.netkiller.cn.conf
server {
    listen       80;
    server_name  www.netkiller.cn;

    charset utf-8;
    access_log  /var/log/nginx/www.netkiller.cn.access.log;

    location / {
        #index  index.html index.htm;
		proxy_pass http://127.0.0.1:8080;
        proxy_set_header    Host    $host;
        proxy_set_header    X-Real-IP   $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }

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

test.jsp 檔案

		<%@ page language="java" import="java.util.*,java.text.SimpleDateFormat" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
	<title>show time</title>
</head>
<body>
<%

	Date date=new Date();
    SimpleDateFormat ss=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String lgtime=ss.format(date);
%>
	<center>
	<h1><%=lgtime%></h1>
	</center>

	<!--# set var="test" value="Hello netkiller!" -->
	<!--# echo var="test" -->

</body>	
</html>		

測試並檢視原始碼,你會看到SSI標籤

	<!--# set var="test" value="Hello netkiller!" -->
	<!--# echo var="test" -->		

解決方案

    location / {
        ssi on;
        proxy_set_header Accept-Encoding "";
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header    Host    $host;
        proxy_set_header    X-Real-IP   $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }		

再次測試,你將看不到SSI標籤,只能看到文字輸出Hello netkiller!