首页主机资讯Ubuntu中nginx配置SSL证书步骤

Ubuntu中nginx配置SSL证书步骤

时间2025-11-25 19:23:04发布访客分类主机资讯浏览485
导读:Ubuntu 中 Nginx 配置 SSL 证书步骤 一 准备与前置检查 准备内容:已解析到服务器的域名(如:example.com、www.example.com),服务器防火墙放行 HTTP/HTTPS(UFW 可用 Nginx Fu...

Ubuntu 中 Nginx 配置 SSL 证书步骤

一 准备与前置检查

  • 准备内容:已解析到服务器的域名(如:example.comwww.example.com),服务器防火墙放行 HTTP/HTTPS(UFW 可用 Nginx Full),域名可访问且 Nginx 已安装并运行。
  • 安装与启动 Nginx(如未安装):
    sudo apt update
    sudo apt install nginx
    sudo systemctl start nginx & & sudo systemctl enable nginx
  • 防火墙放行:
    sudo ufw allow ‘Nginx Full’
    以上确保后续证书获取与访问验证顺利进行。

二 方式一 使用 Let’s Encrypt 与 Certbot 自动部署(推荐)

  • 安装 Certbot 及 Nginx 插件:
    sudo apt update
    sudo apt install certbot python3-certbot-nginx
  • 获取并自动配置证书(同时处理 HTTP→HTTPS 重定向):
    sudo certbot --nginx -d example.com -d www.example.com
    按交互提示选择是否重定向,Certbot 会自动修改 Nginx 配置并加载。
  • 验证与续期:
    • 立即验证:访问 https://example.com,应显示安全锁标识。
    • 自动续期:Let’s Encrypt 证书有效期 90 天,启用系统定时器自动续期:
      sudo systemctl enable certbot.timer & & sudo systemctl start certbot.timer
      如需手动测试续期:
      sudo certbot renew --dry-run
      以上流程适用于 Ubuntu 上的 Nginx,证书路径通常为 /etc/letsencrypt/live/example.com/,包含 fullchain.pemprivkey.pem

三 方式二 手动部署已有或自签名证书

  • 放置证书文件(示例路径,权限设为仅 root 可读):
    sudo mkdir -p /etc/nginx/ssl
    sudo cp server.crt /etc/nginx/ssl/
    sudo cp server.key /etc/nginx/ssl/
    sudo chmod 600 /etc/nginx/ssl/*
  • 配置 HTTP→HTTPS 与 SSL 站点(示例):
    server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
    }
    server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com www.example.com;
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers HIGH:!aNULL:!MD5;
    # 其他业务配置…
    }
  • 检查并重载:
    sudo nginx -t & & sudo systemctl reload nginx
  • 自签名证书仅用于测试或内网,浏览器会提示不受信任。生成自签名证书示例:
    sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
    以上手动方式适合已有证书或需要自签名证书的场景。

四 验证与常见问题

  • 配置语法检查与重载:
    sudo nginx -t & & sudo systemctl reload nginx
  • 在线与命令行验证:
    • 在线工具:SSL Labs Server Test(Qualys)评估安全强度与配置。
    • 命令行:
      openssl s_client -connect example.com:443 -servername example.com
  • 常见问题排查:
    • 端口与防火墙:确认 443 端口开放(UFW 使用 Nginx Full)。
    • 证书路径与权限:证书与私钥路径正确,私钥权限 600
    • 域名与解析:确保域名解析到服务器且访问时 Host 头正确。
    • 续期失败排查:查看日志 /var/log/letsencrypt/,必要时执行 –dry-run 复现问题。
      这些步骤可快速定位大多数 HTTPS 配置与证书问题。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Ubuntu中nginx配置SSL证书步骤
本文地址: https://pptw.com/jishu/755857.html
Ubuntu下如何配置nginx静态资源服务 Debian From Scratch学习曲线

游客 回复需填写必要信息