反向代理 示例一
准备
linux中部署 tomcat (jdk12 tomcat9)
ip : 192.168.33.129 port: 8080 如下图
启动nginx
ip : 192.168.33.129 port: 80 如下图
实现效果 :
配置让nginx 的地址 ip : 192.168.33.129 port: 80 去代理tomcat的地址 ip : 192.168.33.129 port: 8080 . (我的nginx 和 tomcat 部署在一台机子上, 故ip是一样的.)
即我访问 192.168.33.129 : 80 弹出来的应该为tomcat的首页, 而不是nginx首页.
配置nginx
在 nginx 进行请求转发的配置(反向代理配置)
在http->server 中加上:
server_name 192.168.33.129;
location 中加入: proxy_pass http://127.0.0.1:8080;
如下图:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name 192.168.33.129;
location / {
root html;
proxy_pass http://127.0.0.1:8080;
index index.html index.htm;
}
#error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
配置的时候要注意 , 不要用tab, 用空格来代替.
效果:
用80端口由nginx 代理到了 8080 端口实现了tomcat的访问.
反向代理 示例二
实现效果:使用 nginx 反向代理,根据访问的路径跳转到不同端口的服务中
根据不同的路径 /demo8080 和 /demo8081 分别访问不同的服务.
访问 http://192.168.33.129/demo8080/test.html
跳转到: 8080 的服务
访问 http://192.168.33.129/demo8081/test.html
跳转到: 8081 的服务
准备
启动两个tomcat 服务 , 访问端口分别为 8080 和 8081
在8080端口 的webapps 目录下新建 demo8080 目录 , 放入test.html ,内容是 server 8080
在8081端口 的webapps 目录下新建 demo8081目录 , 放入test.html ,内容是 server 8081
以此区别两个服务 .
配置反向代理
在nginx.conf 中配置.
server {
listen 80;
server_name 192.168.33.129;
location ~ /demo8080/{
proxy_pass http://127.0.0.1:8080;
}
location ~ /demo8081/{
proxy_pass http://127.0.0.1:8081;
}
location / {
root html;
proxy_pass http://127.0.0.1:8080;
index index.html index.htm;
}
}
执行重新加载配置
./sbin/nginx -s reload
效果:
附: 示例中 ip都是一样的, 因为资源有限, nginx和tomcat 部署在同一个虚拟机. 效果其实都是一样的.
附:
location 指令
该指令用于匹配 UR
1、= :用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配
成功,就停止继续向下搜索并立即处理该请求。
2、~:用于表示 uri 包含正则表达式,并且区分大小写。
3、~*:用于表示 uri 包含正则表达式,并且不区分大小写。
4、^~:用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字
符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location 块中的正则 uri 和请求字符串做匹配。
注: 如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识