Ubuntu LNMP如何配置SSL证书

518
2025/3/26 12:31:59
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu上配置LNMP(Linux, Nginx, MySQL, PHP)环境的SSL证书,通常使用Let’s Encrypt提供的免费SSL/TLS证书。以下是详细步骤:

1. 安装Certbot

Certbot是一个自动化工具,用于获取和续订Let’s Encrypt证书。

sudo apt update
sudo apt install certbot python3-certbot-nginx

2. 获取SSL证书

使用Certbot获取SSL证书。假设你的域名是example.com

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

Certbot会自动检测Nginx配置文件,并提示你进行一些配置更改。按照提示操作即可。

3. 配置Nginx

Certbot会自动修改你的Nginx配置文件,通常位于/etc/nginx/sites-available/example.com-le-ssl.conf。确保以下内容正确:

server {
    listen 443 ssl;
    server_name example.com www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location / {
        root /var/www/html;
        index index.php index.html index.htm;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
    }

    location ~ /\.ht {
        deny all;
    }
}

4. 启用SSL配置

确保你的Nginx配置文件链接到sites-enabled目录。

sudo ln -s /etc/nginx/sites-available/example.com-le-ssl.conf /etc/nginx/sites-enabled/

5. 测试Nginx配置

测试Nginx配置是否正确。

sudo nginx -t

如果没有错误,重新加载Nginx。

sudo systemctl reload nginx

6. 自动续订证书

Certbot会自动设置一个cron任务或systemd定时任务来定期续订证书。你可以手动测试续订过程:

sudo certbot renew --dry-run

如果没有错误,证书将自动续订并更新到/etc/letsencrypt/live/example.com/目录。

7. 配置防火墙

确保你的防火墙允许443端口的流量。

sudo ufw allow 'Nginx Full'

8. 验证SSL配置

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

通过以上步骤,你就可以在Ubuntu上成功配置LNMP环境的SSL证书。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Ubuntu上怎么运行Windows子系统