温馨提示×

centos nginx ssl配置如何实现全站https

小樊
35
2025-12-03 17:28:03
栏目: 云计算

要在 CentOS 上使用 Nginx 配置全站 HTTPS,你需要完成以下步骤:

  1. 安装 Nginx 和 Certbot: 如果你还没有安装 Nginx,请先安装它。在 CentOS 7 上,你可以使用以下命令安装 Nginx:

    sudo yum install epel-release
    sudo yum install nginx
    

    接下来,安装 Certbot 和 Nginx 插件:

    sudo yum install certbot python2-certbot-nginx
    
  2. 获取 SSL 证书: 使用 Certbot 获取 Let’s Encrypt 提供的免费 SSL 证书。运行以下命令,将 yourdomain.com 替换为你的域名:

    sudo certbot --nginx -d yourdomain.com
    

    Certbot 将自动配置 Nginx 并创建一个名为 /etc/letsencrypt/options-ssl-nginx.conf 的文件,其中包含推荐的 SSL 设置。Certbot 还会创建一个临时文件 /etc/letsencrypt/nginx.conf,其中包含实际的 Nginx 配置。

  3. 备份原始 Nginx 配置文件: 在修改 Nginx 配置文件之前,请先备份原始文件:

    sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup
    
  4. 修改 Nginx 配置文件: 使用文本编辑器打开 /etc/letsencrypt/nginx.conf 文件,找到 server 块,然后添加以下代码:

    server {
        listen 80;
        server_name yourdomain.com www.yourdomain.com;
        location /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }
        location / {
            return 301 https://$host$request_uri;
        }
    }
    

    yourdomain.comwww.yourdomain.com 替换为你的域名。这段代码的作用是将所有 HTTP 请求重定向到 HTTPS。

  5. 重启 Nginx: 保存更改并退出文本编辑器。然后运行以下命令重启 Nginx:

    sudo systemctl restart nginx
    

现在,你的 CentOS 上的 Nginx 已经配置为全站 HTTPS。访问你的域名时,浏览器将显示安全连接。

0