문제

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?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top