搜索 K
Appearance
博客正在加载中...
Appearance
本文演示下如何让 Nginx 分发请求到不同的路径里。
启动两个 Tomcat,其中一个 Tomcat 端口为 8080,另一个 Tomcat 端口为 8081
修改 nginx 监听端口为 9001
使用 nginx 反向代理,根据访问的路径跳转到不同端口的服务中:
访问 localhost:9001/edu/ 跳转到 127.0.0.1:8080
访问 localhost:9001/vod/ 跳转到 127.0.0.1:8081
如何再启动多一个 Tomcat 呢?很简单,再复制一份 Tomcat 的目录,然后修改端口,再次启动 Tomcat 即可:
mkdir /opt/tomcat8181
cd /opt
tar -zxvf apache-tomcat-9.0.73.tar.gz -C /opt/tomcat8181/ 修改 Tomcat8081 的端口为 8081:
cd /opt/tomcat8181/apache-tomcat-9.0.73/conf/
vim server.xml 修改原本的 8080 端口为 8081(在 69 行左右):
<Connector port="8081" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" /> 除此之外,还要修改 shutdown 的端口,将 8005 改为 8015(第 22 行左右),这样才能顺利关闭:
<Server port="8005" shutdown="SHUTDOWN"> 然后启动新的 Tomcat:
cd /opt/tomcat8181/apache-tomcat-9.0.73/bin/
./startup.sh然后访问 8081 端口,能正常访问:
至此,我们就创建了两个 Tomcat 了,一个端口号是 8080,一个端口号是 8081。
为了区分不同的 Tomcat,我们新建两个 HTML 文件,这样就可以根据页面来区分到底是哪个 Tomcat 了。
在 8080 的 Tomcat 中的 webapps 目录下,新建 edu 目录,然后新建 index.html 页面,并写一些内容:
cd /opt/apache-tomcat-9.0.73/webapps/
mkdir edu
echo '<h1>This is 8080 Tomcat</h1>' > edu/index.html 在 8081 的 Tomcat 中的 webapps 目录下,新建 vod 目录,然后新建 index.html 页面,并写一些内容:
cd /opt/tomcat8181/apache-tomcat-9.0.73/webapps/
mkdir vod
echo '<h1>This is 8081 Tomcat</h1>' > vod/index.html 然后我们通过浏览器来测试下访问这两个地址:
修改 nginx.conf 文件:
server {
listen 9001;
server_name 127.0.0.1;
location ~ /edu/ {
proxy_pass http://127.0.0.1:8080;
}
location ~ /vod/ {
proxy_pass http://127.0.0.1:8081;
}
}接下来,就是 reload 下 Nginx 并测试下访问了:
./nginx -s reload 效果:
完整的 Nginx 配置
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 9001;
server_name localhost;
location ~ /edu/ {
proxy_pass http://127.0.0.1:8080;
}
location ~ /vod/ {
proxy_pass http://127.0.0.1:8081;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}