当执行proxy_pass到Tomcat时,Nginx如何将子域添加为参数 [英] How can Nginx add the Subdomain as parameter when a proxy_pass to Tomcat is executed
问题描述
我想要实现的目标
Web应用程序应该能够支持多个子域,而无需在每次新的子域都对nginx或tomcat进行任何更改时用过的。 (我已经对DNS进行了必要的更改以支持通配符子域)
What I am trying to achieve
The web application should be able to support multiple subdomains without having to make any changes on the nginx or tomcat every time a new subdomain is used. (I have already done the required changes to DNS to support wild card subdomains)
Nginx侦听端口80.它在端口8080处对tomcat执行proxy_pass。
nginx应该能够支持多个子域。
Nginx listens to port 80. It does a proxy_pass to tomcat at port 8080. nginx should be able to support multiple subdomain.
我当前的设置基于这个答案。但它没有传递参数
Nginx proxy_pass:是否可以向URL添加静态参数?
每个可能的子域
dynamic_subdomain_1.localhost
dynamic_subdomain_2.localhost
Every possible subdomain
dynamic_subdomain_1.localhost
dynamic_subdomain_2.localhost
nginx设置
server {
listen 80 default_server;
server_name ~^(?<subdomain>.+)\.localhost$;
location / {
set $args ?$args&site=$subdomain;
proxy_pass http://127.0.0.1:8080;
}
}
Nginx在调用时应将子域作为参数附加Tomcat。
Nginx should append the subdomain as a parameter when it invokes Tomcat.
每个子域名对Tomcat的调用应如下所示
http://127.0.0.1:8080?site=dynamic_subdomain_1
http://127.0.0.1:8080?site=dynamic_subdomain_2
我已尝试过上述设置,但查询参数始终显示为空。
I have tried the above setup but the query parameter always shows up as null.
我应该在nginx中做些什么才能使这成为可能呢?
What should I change in nginx to make this possible?
推荐答案
答案比这简单一点。只需获取子域的子字符串并将其用作proxy_pass的参数:
The answer is little bit simpler than that. Just get the substring with the subdomain and use it as a parameter for proxy_pass:
server {
# this matches every subdomain of domain.
server_name .domain;
location / {
set $new_request_uri "";
set $subdomain "";
if ($host ~* "^(.+)\.domain$") {
set $subdomain $1;
# lets assume there are args...
set $new_request_uri "$request_uri&subdomain=$subdomain";
}
# if there are no args add a question mark and the subdomain argument
if ($args = '') {
set $new_request_uri "$request_uri?subdomain=$subdomain";
}
proxy_pass http://127.0.0.1:8080$new_request_uri;
}
}
我考虑了带或不带args的请求。我认为它解决了你的问题。
I considered the request with or without args. I think it solves yout problem.
Alfredo
这篇关于当执行proxy_pass到Tomcat时,Nginx如何将子域添加为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!