问题分析
一台服务器运行多个项目的时候会遇到这样的问题:如果使用同一个tomcat来启动不同项目的话,项目之间会相互影响;如果用多个tomcat运行项目,那么在访问项目的时候又不能都使用80端口,还要加上端口号,显得很麻烦又不美观。
考虑用Nginx实现转发,目标是通过访问不同的域名实现对不同tomcat上运行的项目的跳转,例如访问www.a.com 跳转到本地的8088端口的项目,访问www.b.com跳转到本地的8080端口的项目。
配置
修改本地的hosts文件
修改IP映射文件,添加本地IP地址解析,文件位置是C:\Windows\System32\drivers\etc
127.0.0.1 www.a.com
127.0.0.1 www.b.com
这样浏览器访问www.a.com和www.b.com的时候就会直接访问本机的地址,不会去网络上询问IP地址。
添加自定义的Nginx配置文件
在nginx根目录下新建文件夹“vhost”,新建a.conf 、b.conf两个配置文件,内容如下
a.conf
server {
listen 80;
server_name www.a.com;
location /fileServer {
alias F:\test;
autoindex on;# 显示目录
autoindex_exact_size on;# 显示文件大小
autoindex_localtime on;# 显示文件时间
allow all;
index index.html index.htm;
}
}
b.conf
server {
listen 80;
server_name www.b.com;
location / {
proxy_pass http://127.0.0.1:8088;
proxy_set_header Host $proxy_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Via "nginx";
}
}
这里我把www.a.com对应的项目设置成文件服务器,www.b.com对应的项目设置成本地端口号为8088对应的项目。
修改Nginx的配置文件
在conf文件夹下的nginx.conf文件中追加如下配置
include ../vhost/*.conf;
这样就会去读取上边自定义的配置文件。
运行项目
启动8088端口对应的tomcat,启动nginx
验证结果
浏览器访问www.a.com,结果如图
这里写图片描述
浏览器访问www.b.com ,结果如图
这里写图片描述
结果
通过简单配置实现了都使用80端口,通过不同的域名来访问不同的项目。如果需要添加其他项目了,就再添加c.conf配置项目,一个配置文件对应一个项目,维护起来也方便一些。
————————————————
版权声明:本文为CSDN博主「活在戏中吧」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_21856521/article/details/81945458
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
#www.abc.com
server {
listen 80;
server_name localhot;
location / {
proxy_pass http://ylbzj.nanyag.gov.cn:80;
proxy_set_header Host $proxy_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Via "nginx";
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}