温馨提示×

LNMP环境Ubuntu下如何配置SSL

小樊
42
2025-12-29 23:40:44
栏目: 云计算

在Ubuntu系统上配置LNMP(Linux, Nginx, MySQL, PHP)环境的SSL,通常需要以下几个步骤:

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. 验证配置

Certbot会自动验证你的域名是否正确配置了SSL。如果一切正常,你会看到一个成功消息。

4. 自动续订证书

Let’s Encrypt证书的有效期是90天,Certbot会自动设置一个cron任务来定期续订证书。

你可以手动测试续订过程:

sudo certbot renew --dry-run

如果没有问题,Certbot会输出续订成功的信息。

5. 配置Nginx

如果你需要手动配置Nginx,可以编辑Nginx配置文件(通常位于/etc/nginx/sites-available/目录下)。

例如,创建一个新的配置文件example.com.conf

sudo nano /etc/nginx/sites-available/example.com.conf

添加以下内容:

server {
    listen 80;
    server_name example.com www.example.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

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;

    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 / {
        try_files $uri $uri/ =404;
    }
}

启用配置文件:

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

测试Nginx配置:

sudo nginx -t

重启Nginx服务:

sudo systemctl restart nginx

6. 配置防火墙

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

sudo ufw allow 'Nginx Full'

7. 测试SSL连接

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

通过以上步骤,你应该能够在Ubuntu系统上成功配置LNMP环境的SSL。

0