背景
为了安全,我们一般不将服务端口暴露出去,通过nginx配置路由可以实现不加端口直接访问服务。
例如:直接通过端口访问服务:http://example.com:8080/ , http://example.com:9090/
不加端口直接访问服务:http://example.com/first/ , http://example.com/second/
注意: 其中 http://example.com:8080/ 还需要支持websocket连接
实现
通过配置nginx的路由实现不加端口访问服务
server {
listen 80;
server_name localhost;
#charset koi8-r;
access_log logs/host.access.log main;
location ^~ /first/ {
proxy_pass http://47.98.37.11:8080/;
# support websocket connect
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# solve EOFException error
proxy_read_timeout 3600s;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
}
location ^~ /second/ {
proxy_pass http://47.98.37.11:9090/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
}
}
注意: 因为8080服务的websocket连接心跳时间太长,导致websocket重复断连,并报错:
java.io.EOFException: null
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.fillReadBuffer(NioEndpoint.java:1206)
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.read(NioEndpoint.java:1140)
通过配置: proxy_read_timeout 3600s; 解决。