Nginx 配置域名及手动安装 Let’s Encrypt 完整指南
Nginx 配置域名及手动安装 Let’s Encrypt 完整指南
1. 配置 Nginx 服务
1.1 编辑 Nginx 配置文件
打开 Nginx 的主配置文件或站点配置文件(例如 /usr/local/lighthouse/softwares/nginx/conf/nginx.conf
):
sudo vim /usr/local/lighthouse/softwares/nginx/conf/nginx.conf
1.2 添加域名的 Server 块
在配置文件中为您的域名添加以下内容:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
# 配置 .well-known 路径以供 Let's Encrypt 验证使用
location /.well-known/acme-challenge/ {
root /usr/share/nginx/html;
}
# 将其他流量重定向到 HTTPS
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
# 配置 SSL 证书路径
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://127.0.0.1:8006; # 根据您的应用端口配置
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
1.3 创建 .well-known 目录
Let's Encrypt 验证过程中需要访问 .well-known
文件夹,创建该目录:
sudo mkdir -p /usr/share/nginx/html/.well-known/acme-challenge
sudo chmod -R 755 /usr/share/nginx/html/.well-known
1.4 重启 Nginx 服务
检查配置是否正确并重新加载 Nginx:
sudo /usr/local/lighthouse/softwares/nginx/sbin/nginx -t
sudo /usr/local/lighthouse/softwares/nginx/sbin/nginx -s reload
2. 手动安装 Let’s Encrypt 证书
2.1 停止 Nginx 服务
Certbot 在 standalone 模式下需要占用 80 端口,因此需要先停止 Nginx:
sudo /usr/local/lighthouse/softwares/nginx/sbin/nginx -s stop
2.2 使用 Certbot 申请证书
运行以下命令为域名申请证书:
sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com
-
如果证书申请成功,您将看到如下提示:
Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/yourdomain.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/yourdomain.com/privkey.pem
2.3 启动 Nginx 服务
申请完成后,重新启动 Nginx:
sudo /usr/local/lighthouse/softwares/nginx/sbin/nginx
3. 测试与验证
3.1 验证域名访问
在浏览器中访问:
http://yourdomain.com
应自动跳转到https://yourdomain.com
- 确认 HTTPS 是否生效,以及浏览器是否显示安全锁标志。
3.2 验证证书路径
检查生成的证书路径是否正确:
sudo ls -l /etc/letsencrypt/live/yourdomain.com/
4. 配置证书自动续期
4.1 测试续期功能
运行以下命令测试证书续期是否正常:
sudo certbot renew --dry-run
4.2 设置自动续期任务
编辑系统的 crontab
文件:
sudo crontab -e
添加以下内容:
0 0 * * * certbot renew --quiet && /usr/local/lighthouse/softwares/nginx/sbin/nginx -s reload
5. 其他注意事项
-
检查防火墙配置: 确保服务器允许 80 和 443 端口的外部访问:
sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --permanent --add-service=https sudo firewall-cmd --reload
-
清理历史文件: 如果之前申请失败或配置错误,清理旧的
.well-known
文件夹:sudo rm -rf /usr/share/nginx/html/.well-known
按照以上步骤配置,您的域名应该能够正确通过 Nginx 服务和 HTTPS 访问。
No previous page