問題描述
應用在客戶產線環境部署時,要求只需要輸入域名就可以直接訪問到應用,而不用輸入完整的應用訪問路徑。
項目架構
前端使用nginx作為反向代理和負載均衡,后端部署多個tomcat實例。
Web應用直接部署到catalina_home/webapps目錄下,訪問時必須帶上應用上下文路徑:http://mmm.chench.com/mmm。
解決方案
在前端nginx上配置根據請求參數進行路徑重定向。
具體來說,就是判斷用戶請求uri是否為“/”,以此來判斷用戶是否只輸入域名。
在location之前添加如下配置語句:
if ($uri = '/') {
rewrite ^/ https://$server_name/mmm/home.do permanent;
}
詳細配置:
http {
upstream 8080 {
server 192.168.10.100:8080;
server 192.168.10.200:8080;
}
server {
listen 443 ssl;
server_name mmm.chench.com;
ssl on;
ssl_certificate /etc/nginx/ssl/mmm.chench.com.crt;
ssl_certificate_key /etc/nginx/ssl/mmm.chench.com.key;
if ($uri = '/') {
rewrite ^/ https://$server_name/mmm/home.do permanent;
}
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://8080;
}
}
}
當然,還可以直接使用location的精確匹配規則實現(使用等於符號將第一個location配置為精確匹配)。
location = / {
proxy_pass http://8080/mmm/home.do;
}
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://8080;
}
實現原理
1.nginx支持表達式判斷請求uri並可以進行路徑重定向。
2.nginx配置location支持精確匹配。
在nginx中可以通過如上2種方式實現直接通過域名訪問應用。
【參考】
https://xuexb.com/post/nginx-url-rewrite.html nginx配置url重寫
http://blog.sina.com.cn/s/blog_6d579ff40100wsip.html Nginx 變量漫談(六)