ubuntu

Ubuntu LNMP环境下如何配置SSL证书

小樊
41
2025-06-21 04:01:42
栏目: 云计算

在Ubuntu LNMP(Linux, Nginx, MySQL, PHP)环境下配置SSL证书,可以按照以下步骤进行:

1. 获取SSL证书

首先,你需要获取一个SSL证书。你可以从Let’s Encrypt免费获取,或者购买一个商业证书。

使用Let’s Encrypt获取证书

  1. 安装Certbot:

    sudo apt update
    sudo apt install certbot python3-certbot-nginx
    
  2. 运行Certbot获取证书:

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

    按照提示完成证书的获取和安装。

2. 配置Nginx

Certbot会自动修改你的Nginx配置文件以启用HTTPS。你可以检查并确认配置是否正确。

  1. 打开Nginx配置文件:

    sudo nano /etc/nginx/sites-available/yourdomain.com
    
  2. 确保配置文件中有以下内容:

    server {
        listen 80;
        server_name yourdomain.com www.yourdomain.com;
        return 301 https://$host$request_uri;
    }
    
    server {
        listen 443 ssl;
        server_name yourdomain.com www.yourdomain.com;
    
        ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
    
        root /var/www/yourdomain.com;
        index index.php index.html index.htm;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
        }
    
        location ~ /\.ht {
            deny all;
        }
    }
    
  3. 测试Nginx配置:

    sudo nginx -t
    
  4. 重新加载Nginx:

    sudo systemctl reload nginx
    

3. 配置自动续期

Let’s Encrypt证书每90天会过期一次,因此需要设置自动续期。

  1. 编辑Certbot的续期脚本:

    sudo crontab -e
    
  2. 添加以下行以每天运行一次续期检查:

    0 */12 * * * certbot renew --post-hook "systemctl reload nginx"
    

4. 验证配置

打开浏览器,访问https://yourdomain.com,确保SSL证书正确安装并且网站可以正常访问。

5. 其他注意事项

通过以上步骤,你应该能够在Ubuntu LNMP环境下成功配置SSL证书。

0
看了该问题的人还看了