如何将所有HTTP请求redirect到HTTPS并将所有不存在的子域redirect到一个特定的域

我已经有一个工作configuration来redirect所有不存在的子域到一个特定的域。 现在我想添加一个configuration,将所有HTTP请求redirect到同一个域上的HTTPS。

这个configuration文件的子域redirect:

# redirect any non-existent subdomain (blah.domain.de -> domain.de) server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 301 https://domain.de$request_uri; } 

这是我尝试用于HTTP-> HTTPS的configuration:

 # redirect any HTTP request to its HTTPS address (http://domain.de/blub -> https://domain.de/blub) server { listen 80 default_server; listen [::]:80 default_server; server_name domain.de mail.domain.de admin.domain.de; return 301 https://$server_name$request_uri; } 

但是这不起作用,因为default_server被定义了两次。 如何结合这两个function?

我真的必须添加第二个configuration到每个单一的子域configuration?

您需要从后面的configuration中删除default_server ,并将每个域名添加到server_name部分。

那么你需要使用return 301 https://$host$request_uri; 为redirect语句。

Nginx不支持嵌套的if语句(它也不支持复杂的条件)。

我以另一种方式工作。 我通过SSL片段将其添加到每个子域configuration中。 每个子域configuration都包含相同的SSLconfiguration。 所以我添加到这个configuration一个http检查:

 if ($scheme = http ){ rewrite ^ https://$server_name$request_uri permanent; } # ... followed by ssl config 

这包括在每个子域服务器块configuration中:

 include snippets/ssl.conf; 

它做我想要的。 也许有另外一种方式,不要把它包含到每个子域中。