简体   繁体   English

Nginx 通配符子域重定向到非 www

[英]Nginx wildcard subdomain redirect to non-www

I have a domain set up with wildcard subdomains for white label access.我有一个使用通配符子域设置的域,用于白标签访问。 I'm trying to safeguard against people typing in http://www.subdomain.domain.com/ but struggling to find a solution.我正在努力防止人们在http://www.subdomain.domain.com/输入但正在努力寻找解决方案。 (I already have a rewrite in action to always use a secure protocol.) (我已经进行了重写以始终使用安全协议。)

My current setup is this (well, the relevant part):我目前的设置是这样的(好吧,相关部分):

server {
    listen 80;
    server_name  domain.com *.domain.com;
    rewrite ^ https://$http_host$request_uri? permanent;
}

server {
    listen 443;
    ssl on;
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/certificate.key;
    server_name domain.com *.domain.com;

    ...
}

What I have achieved is that http://domain.com and http://sub.domain.com both redirect to the https protocol, in other words https://domain.com and https://sub.domain.com respectively.我实现的是http://domain.comhttp://sub.domain.com都重定向到https协议,换句话说https://domain.comhttps://sub.domain.com分别。 What I'd still like to achieve on top is that both http://www.domain.com and https://www.domain.com redirect to https://domain.com and that both http://www.sub.domain.com and https://www.sub.domain.com redirect to https://sub.domain.com as well.我仍然希望实现的是http://www.domain.comhttps://www.domain.com重定向到https://domain.comhttp://www.sub.domain.comhttps://www.sub.domain.com重定向到https://sub.domain.com

Could anyone help, please?请问有人可以帮忙吗?

(PS: I was even thinking of applying a global nginx setup to remove the www part of the URL for ALL domains running on the same server at once if that's an option.) (PS:我什至考虑应用全局 nginx 设置来删除在同一服务器上运行的所有域的 URL 的www部分,如果这是一个选项。)

To drop the leading www.删除领先的www. sequence from the requested server name, place this if block near the top of your SSL server container (before any other URI processing directives):从请求的服务器名称中提取序列,将此if块放在 SSL 服务器容器顶部附近(在任何其他 URI 处理指令之前):

if ($http_host ~* ^www\.(.*)$ ) 
{ 
    return 301 $scheme://$1$request_uri;
}

Generally if should be used very carefully , but it is perfectly fine in this case.通常if 应该非常小心地使用,但在这种情况下完全没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM