Nginx:如何仅将主域与 server_name 匹配 [英] Nginx: How to match ONLY the main domain with server_name

查看:60
本文介绍了Nginx:如何仅将主域与 server_name 匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是将 example.com 重定向到 www.example.com 而不将 any 子域重定向到 www>.

My goal is to redirect example.com into www.example.com without redirecting any subdomain to www.

这就是我所拥有的:

server {
  listen 443;
  server_name example.com;
  return 301 https://www.$server_name$request_uri;
}

使用此配置每个子域(例如:foo.example.com)都被重定向到 www.example.com,而不仅仅是如我所愿,没有子域(example.com)的主域名.

With this configuration every subdomain (ex: foo.example.com) gets redirected into www.example.com, not just the main one without subdomain (example.com), as I would like.

我尝试清理缓存(也从其他浏览器清理),结果相同.

I tried cleaning cache (and also doing it from other browsers) with same results.

server_name 匹配子域的证据是,如果我将重定向 url 更改为:https://www.$host$request_uri 然后:

The proof that the server_name is matching subdomains is that if I change the redirection url to: https://www.$host$request_uri then:

foo.example.com 被重定向到 www.foo.example.com.

推荐答案

实际上,example.com 只匹配主域.

Actually, example.com does only match the main domain.

但如果 hostname 不匹配任何 server_name(在您的示例中,您的子域不匹配,因为主域只有一个服务器规则),将使用 默认服务器如果你没有't 在 listen 参数中使用 default_server 标记指定它,它默认使用第一个服务器,在您的情况下,它是主域的重定向规则.

But if the hostname doesn't match any server_name (and in your example, your subdomains do not as there is only one server rule for the main domain), the default server will be used, which, if you didn't specify it with the default_server tag in the listen parameter, it uses by default the first server, which, in your case, is the redirection rule for the main domain.

您的子域不匹配任何规则,因此它们被回调到您设置的唯一规则,即重定向.

Your subdomains aren't matching any rule, so they are being called back to the only rule you setted, the redirection.

您需要为子域制定特定规则:

You need to have a specific rule for subdomains:

server {
  listen 443;
  server_name *.example.com;
  # do something, or leave it blank for default nginx page
}

这将阻止子域使用默认服务器,因此被重定向到 www,但它们没有配置为什么都不做,因此将显示默认的 nginx 页面.我建议直接为每个子域指定您想要的行为,或者将注释替换为所有子域的实际预期行为.

This will prevent the subdomains from using the default server and so, being redirected to www, but they are not configured for doing nothing, so a default nginx page will show. I would recomend to directly specify the behaviour you want for each of the subdomains, or replacing the comment with the actual expected behaviour for all of them.

这篇关于Nginx:如何仅将主域与 server_name 匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆