You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Certbot为Nginx生成包含www与非www的有效证书?

解决Nginx中非www域名443端口重定向到www的问题

Hey there! Let's fix that non-www HTTPS redirect issue for your Nginx setup. From what you described, your www domain is working fine, but the non-www HTTPS isn't redirecting properly—here's how to sort it out step by step:

1. 调整非www域名的443配置块

找到你那个不带www的443端口配置块,一定要保留Certbot生成的SSL相关配置(不然访问非www HTTPS会触发证书错误),然后添加核心重定向规则。最终配置应该类似这样:

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name example.com; # 替换成你的非www域名

    # 保留Certbot自动生成的SSL配置(内容以你实际生成的为准)
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # 永久跳转到www版本的HTTPS,对SEO友好且让浏览器记住规则
    return 301 https://www.example.com$request_uri;
}

2. 确认Certbot为非www域名签发了证书

如果上面的SSL文件路径不存在,说明Certbot还没为非www域名生成证书。你可以重新运行Certbot,同时指定两个域名:

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

这样Certbot会生成包含双域名的证书,之后你再把非www的443配置块调整回上面的重定向规则即可。

3. 优化80端口的重定向配置

你之前的80端口用了Certbot生成的if语句,其实可以简化成更高效的写法(Nginx中if在部分场景下存在性能隐患):

server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;
    # 直接将所有HTTP请求重定向到www的HTTPS
    return 301 https://www.example.com$request_uri;
}

4. 验证配置并重启Nginx

每次修改配置后,先检查语法是否正确:

sudo nginx -t

如果输出显示nginx: configuration file /etc/nginx/nginx.conf test is successful,就重启Nginx让配置生效:

sudo systemctl restart nginx

调整完成后,不管用户访问http://example.com、http://www.example.com还是https://example.com,都会自动跳转到https://www.example.com,且不会出现证书错误。

内容的提问来源于stack exchange,提问作者Mattis Erngren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:20:28