How can Nginx add the Subdomain as parameter when a proxy_pass to Tomcat is executed

时光毁灭记忆、已成空白 提交于 2019-12-22 10:05:16

问题


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 listens to port 80. It does a proxy_pass to tomcat at port 8080. nginx should be able to support multiple subdomain.

My current setup is based on this answer. But it is not passing the parameter
Nginx proxy_pass : Is it possible to add a static parameter to the URL?

Every possible subdomain
dynamic_subdomain_1.localhost
dynamic_subdomain_2.localhost

nginx setup

server {
    listen 80 default_server;

    server_name ~^(?<subdomain>.+)\.localhost$;

    location / {
        set $args ?$args&site=$subdomain;
        proxy_pass http://127.0.0.1:8080;
    }
}

Nginx should append the subdomain as a parameter when it invokes Tomcat.

The Calls to Tomcat should be as follows for each subdomain

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.

What should I change in nginx to make this possible?


回答1:


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;              
  }                                                              
} 

I considered the request with or without args. I think it solves yout problem.

Alfredo



来源:https://stackoverflow.com/questions/22771544/how-can-nginx-add-the-subdomain-as-parameter-when-a-proxy-pass-to-tomcat-is-exec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!