我正在尝试在 Ubuntu 16.04 上使用 Let's Encrypt 保护 Nginx。
mydomain.conf 文件前获取 SSL 证书
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
mydomain.conf 文件后获取 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
为什么重定向次数太多?
第二个服务器块的用途是什么?
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://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;
}