概述

在某网络论坛上遇到需要Nginx泛域名反向代理且反向代理的后端域名前缀需与访问的域名前缀相同。

需要通过访问abc.test1.ym68.cc(abc为随机值)来实现反向代理后端HOST为abc.test2.ym68.cc(域名前缀访问一致)

处理办法

办法一

直接通过server_name匹配域名前缀信息。

server {
    listen  80;
    server_name ~^(?<subdomain>.+).test1.ym68.cc$;
    index index.html;

    # 缓存静态页面
    location ~ \.html$ {
        # 配置后端服务器
        proxy_pass http://127.0.0.1;
        proxy_redirect off;
        # 回源HOST
        proxy_set_header Host $subdomain.test2.ym68.cc;
        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
        # 隐藏由proxy响应客户端时指定的首部;
        proxy_hide_header Cache-Control ;
    }
}
办法二

通过if判断配置变量

server {
    listen      80;
    server_name *.test1.ym68.cc;
    index index.html index.htm index.php;

    # 定义域名前缀
    if ($host ~ "^(.*)\.test1\.ym68\.cc$") {
      set $subdomain $1;
    }

    # 缓存静态页面
    location ~ \.html$ {
        # 配置后端服务器
        proxy_pass http://127.0.0.1;
        proxy_redirect off;
        # 回源HOST
        proxy_set_header Host $subdomain.test2.ym68.cc;
        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
        # 隐藏由proxy响应客户端时指定的首部;
        proxy_hide_header Cache-Control ;
    }

}
重启Nginx
[root@localhost ~]# systemctl restart nginx
END

本文标题:Nginx使用泛域名反向代理及后端动态前缀

本文作者:宇宙最帅的男人

本文链接:https://lolicp.com/nginx/202128292.html

版权声明:转载或者引用本文内容请注明来源及原作者,本文著作权归作者 (宇宙最帅的男人) 所有。

除非另有说明,本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

最后修改:2021 年 10 月 28 日
如果觉得我的文章对你有用,请随意赞赏