在Tomcat前端加反向代理服務器,在同一臺主機上構建nginx
[root@tomcat ~]# yum install nginx
Installed:
nginx.x86_64 1:1.12.2-1.el7
配置nginx能夠把請求反代給Tomcat,兩種方式
- 把所有請求都反代過去,無論是靜態還是動態,這不是一種理想的方式
- 可以把jsp
java所寫的代碼,一般有兩種資源后綴,.do,另外一種是.jsp,假如運行在Tomcat之上,因此去匹配請求的URL后綴,而后,只把do 和 jsp 結尾的反代給Tomcat,而靜態的,都由自己進行處理
假設動靜資源都放在一起了,先說一個主機,動靜資源都在一起,都在/usr/share/tomcat/webapps/目錄下,nginx的根路徑也應該指向/usr/share/tomcat/webapps/,假如說主站是在/root目錄下,在nginx上還需要專門加一個location,或者是把根直接指向/root目錄,也可以
修改nginx配置文件
[root@tomcat /etc/nginx]# vim nginx.conf
server {
listen ??????80 default_server;
listen ??????[::]:80 default_server;
server_name ?_;
root ???????/usr/share/tomcat/webapps/ROOT/;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
?location ~* \.(jsp|do)$ {
????????????????proxy_pass http://127.0.0.1:8080;
????????}
因為nginx自己不會去找ROOT,所以需要寫上
127.0.0.1:8080; 使用localhost上的虛擬主機進行請求響應,或者使用本機的IP地址也是一樣的,使用本機的IP,也是localhost進行響應的,除非是使用server1才會由后端server1上的虛擬主機進行響應。如果地址寫的是server1:8080,那么nginx所在的機器效可以解析server1才可以,否則無法完成代理
啟動服務
[root@tomcat /etc/nginx]# systemctl restart nginx
[root@tomcat /etc/nginx]# ss -ntl
State ?????Recv-Q Send-Q ???Local Address:Port ??????????????????Peer Address:Port
LISTEN ????0 ?????128 ?????????????????:::80 ??????????????????????????????:::*
LISTEN ????0 ?????100 ?????????????????:::8080 ????????????????????????????:::*
LISTEN ????0 ?????100 ?????????????????:::8009 ????????????????????????????:::*
訪問測試
[root@server2 ~]# curl 192.168.111.101
<html>
<head><title>403 Forbidden</title></head>
注意:對方的默認資源頁面是index.jsp
在nginx上配置的時候,沒表明.jsp的文件可以當做默認主頁面,所以就把index.html請求到后端去了,后端主機就沒有
修改配置文件進行適配
[root@tomcat ~]# vim /etc/nginx/nginx.conf
server {
listen ??????80 default_server;
listen ??????[::]:80 default_server;
server_name ?_;
root ???????/usr/share/tomcat/webapps/ROOT/;
index ??index.jsp index.html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
location ~* \.(jsp|do)$ {
proxy_pass http://127.0.0.1:8080;
}
重新加載配置文件
[root@tomcat ~]# nginx -s reload
訪問測試
[root@server2 ~]# curl 192.168.111.101 -I
HTTP/1.1 200 OK
Server: nginx/1.12.2
點擊主頁面上的Manager按鈕無法跳轉過去,因為nginx去找ROOT目錄下的host-manager/html文件去了
location需要單獨定義,和每個應用程序,在nginx上直接進行代理而且有多個應用,每一個應用都需要單獨定義一個location,而且對于manager資源,頁面文件還是在html目錄下,所以location要定義好,指到manager還不夠,還需要指定heml,因為默認資源時靜態的,叫做index.html,而且是放在manager目錄中的。還需要額外添加location。好在,像這種manager,一般也不應該在前端服務網關代理
本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/92691