如何在 nginx 中将子域作为 proxy_pass 值传递? [英] How can i pass subdomain as proxy_pass value in nginx?
问题描述
我目前处于需要获取/捕获子域并将该子域值传递给 Nginx 配置中的 proxy_pass 的情况.
i am currently in situation where i need to get/catch sub-domain and pass that sub-domain value to proxy_pass in Nginx config.
例如
如果用户输入
http://google.com.mydomain.com
那么它应该做代理传递
proxy_pass http://www.google.com/;
在上面的例子中 google.com
是 sub-domain
in above example google.com
is sub-domain
这可行吗?我怎样才能在 nginx 中实现这样的目标?
can this be doable ? How can i achieve something like that in nginx ?
目前我使用的配置是在配置文件中对子域值进行硬编码,但是有很多子域,所以我需要这样做,但不知道正确的语法.
currently i am using configuration where sub-domain values are hard-coded in config files , but there are many sub-domains , so i need to do it like this way, but don't know correct syntax.
server {
listen 80;
server_name subdomain.domain.com;
charset utf-8;
location / {
proxy_pass http://www.subdomain/;
}
}
我使用 * 作为 A 记录将所有子域重定向到我的网络主机,即通配符 DNS.
I am using * as A record to redirect all sub-domains to my web-host, i.e. wildcard DNS.
更新:
我从 https://stackoverflow.com/a/22774520/1642018
server {
listen 80;
# this matches every subdomain of domain.
server_name .domain.com;
location / {
set $subdomain "";
if ($host ~* "^(.+)\.domain.com$") {
set $subdomain $1;
}
proxy_pass http://$subdomain;
}
}
但请求显示的是我的默认页面,该页面位于我的默认 Web 根目录中.
but the request is showing my default page which is in my default web root.
推荐答案
两件事.
1- 解析器(用于您的 nginx 的 dns 服务器以解析 google.com,您可以在主机上添加或者您可以添加解析器语句)
1- A resolver (a dns server for your nginx in order to resolve google.com, you may add at your hosts or you are able to add resolver statement)
2- 您需要解决您的客户将如何处理不同域的问题,我的意思是 google.com 与 google.com.ar 或 google.fr 不同)
2- You will need to resolve how your client will deals with different domains, I mean google.com is different than google.com.ar or google.fr)
在这个例子中,我为你的例子 google.com 做了工作
At this example I made work it for your example google.com
worker_processes 4;
error_log /var/log/nginx/error.log;
events {
worker_connections 1024;
}
http {
server {
listen 80;
location / {
set $subdomain "";
if ($host ~* "^(.+)\.domain.com$") {
set $subdomain $1;
}
resolver 8.8.8.8;
proxy_pass "http://$subdomain.com";
}
}
}
希望这个配置对你有帮助.
I hope that this configuration helps to you.
这篇关于如何在 nginx 中将子域作为 proxy_pass 值传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!