java - 当执行到 Tomcat 的 proxy_pass 时,Nginx 如何将子域添加为参数

标签 java tomcat nginx dns wildcard-subdomain

我正在努力实现的目标
Web 应用程序应该能够支持多个子域,而无需在每次使用新子域时对 nginx 或 tomcat 进行任何更改。 (我已经对 DNS 进行了必要的更改以支持通配符子域)

Nginx 监听 80 端口,它在 8080 端口做一个 proxy_pass 给 tomcat。 nginx 应该能够支持多个子域。

我当前的设置基于此答案。但是它没有传递参数
Nginx proxy_pass : Is it possible to add a static parameter to the URL?

每个可能的子域
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 时应该附加子域作为参数。

每个子域对 Tomcat 的调用应如下所示

http://127.0.0.1:8080?site=dynamic_subdomain_1
http://127.0.0.1:8080?site=dynamic_subdomain_2

我已尝试上述设置,但查询参数始终显示为空。

我应该在 nginx 中更改什么才能使这成为可能?

最佳答案

答案比这简单一点。只需获取带有子域的子字符串并将其用作 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 的请求。我认为它可以解决您的问题。

阿尔弗雷多

关于java - 当执行到 Tomcat 的 proxy_pass 时,Nginx 如何将子域添加为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22771544/

相关文章:

java - 通过 main 运行的同一类的两个实例 - 它们与 main 的每个线程相关联的唯一标识符是什么?

java - ActionListener 不适用于所有对象

spring - 如何在 Eclipse 中运行以下 spring 示例?

NGINX 上的 SSL 终止

django - Nginx/Django : Accessing static files results in 403 Forbidden

node.js - 在 ElasticBeanstalk 中的 nginx 服务器上启用 cors?

java - Java 中的 printf() 功能与 CharBuffer 或类似的东西相结合

java.security.InvalidKeyException : Wrong key size during decryption

java - 如何在没有 JSP 的情况下使用 TOMCAT 和 Jackson 在 SPRING MVC 中将 POJO 转换为 JSON?

maven - 在 Intellij idea ultimate2017.2 中运行 maven webapp 时出错 : Caused by: java. lang.NoClassDefFoundError: Lorg/slf4j/Logger