mydomain.com 重定向次数过多。ERR_TOO_MANY_REDIRECTS

我正在尝试在Ubuntu 16.04上使用Let's Encrypt来保护Nginx。
在获取SSL证书之前,需要编辑mydomain.conf文件。
server {
    server_name mydomain.com www.mydomian.com ;
    # Tell Nginx and Passenger where your app's 'public' directory is
    root /var/www/backup/mycode/public;
    # Turn on Passenger
    passenger_enabled on;
    rails_env development;
    passenger_ruby /usr/local/rvm/gems/ruby-2.5.6/wrappers/ruby;

}

http://mydomain.com/运行良好。

我尝试通过获取SSL证书来实现。

sudo certbot --nginx -d mydomain.com -d www.mydomain.com

结果是
Your existing certificate has been successfully renewed, and the new certificate
has been installed.

The new certificate covers the following domains: https://mydomain.com and
https://www.mydomain.com

在获得SSL证书之后,我的域名配置文件

server {
    server_name mydomain.com www.mydomain.com ;
    # Tell Nginx and Passenger where your app's 'public' directory is
    root /var/www/backup/mydomain.com/public;
    # Turn on Passenger
    passenger_enabled on;
    rails_env development;
    passenger_ruby /usr/local/rvm/gems/ruby-2.5.6/wrappers/ruby;




    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = www.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    server_name mydomain.com www.mydomain.com ;
    listen 80;
    return 404; # managed by Certbot

}

http://mydomain.com/ 正在重定向到 https://mydomain.com/ 太多次

mydomain.com redirected you too many times.
ERR_TOO_MANY_REDIRECTS

为什么会重定向太多次? 第二个服务器块的目的是什么?
服务器 { 如果 ($host = www.mydomain.com) { 返回 301 https://$host$request_uri; } # 由 Certbot 管理
如果 ($host = mydomain.com) { 返回 301 https://$host$request_uri; } # 由 Certbot 管理
server_name mydomain.com www.mydomain.com ; listen 80; 返回 404; # 由 Certbot 管理 }
如何使所有重定向都指向 https://www.mydomain.com/
1个回答

这个块是问题的原因,就像你怀疑的那样。
server {
    if ($host = www.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    server_name mydomain.com www.mydomain.com ;
    listen 80;
    return 404; # managed by Certbot

}

这个服务器块将用户重定向到 https。但是,它也会把 https 重定向到 https,这就导致了问题。你可以将其更改为:
server {
    listen 80;
    server_name mydomain.com www.mydomain.com;
    return 301 https://mydomain.com$request_uri;
}