例如,我想将域名 sunzhongwei.com 自动跳转到 www.sunzhongwei.com。
Nginx 配置
server {
# 默认是 80 端口
server_name sunzhongwei.com;
return 301 $scheme://www.sunzhongwei.com$request_uri;
}
验证配置,并重新加载配置
nginx -t
nginx -s reload
使用 certbot 自动安装免费的 SSL 证书,并自动修改 Nginx 配置
certbot --nginx -d sunzhongwei.com
certbot 修改后的 Nginx 配置
server {
server_name sunzhongwei.com;
return 301 $scheme://www.sunzhongwei.com$request_uri;
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/sunzhongwei.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/sunzhongwei.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 = sunzhongwei.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name sunzhongwei.com;
listen 80;
return 404; # managed by Certbot
}
测试
在浏览器中输入
http://sunzhongwei.com 和 https://sunzhongwei.com,会看到都自动跳转到了 https://www.sunzhongwei.com。
验证成功。
警告信息
但是,如果我自己直接配置 443 端口,会报警告
2024/08/18 05:54:03 [warn] 1573658#1573658: protocol options redefined for 0.0.0.0:443 in /etc/nginx/conf.d/www.sunzhongwei.com.conf:67
2024/08/18 05:54:03 [warn] 1573658#1573658: protocol options redefined for 0.0.0.0:443 in /etc/nginx/conf.d/www.sunzhongwei2.com.conf:31
没有搞明白是什么问题,还是按照上面的配置即可。
微信关注我哦 👍
我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式