在Ubuntu上配置LNMP(Linux, Nginx, MySQL, PHP)以使用SSL涉及几个步骤。以下是一个基本的指南,帮助你设置SSL证书并配置Nginx以使用HTTPS。
Certbot是一个自动化的工具,用于获取和续订Let’s Encrypt的SSL证书。你可以使用以下命令安装Certbot:
sudo apt update
sudo apt install certbot python3-certbot-nginx
使用Certbot获取SSL证书。运行以下命令并按照提示操作:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
将yourdomain.com和www.yourdomain.com替换为你的实际域名。Certbot会自动配置Nginx并重启服务。
Certbot会自动验证你的域名所有权,并配置Nginx以使用HTTPS。你可以通过访问https://yourdomain.com来验证配置是否成功。
Let’s Encrypt的证书有效期为90天。Certbot会自动设置一个cron作业来定期检查并续订证书。你可以手动测试续订过程:
sudo certbot renew --dry-run
如果没有错误,证书将成功续订。
如果你需要进一步自定义Nginx配置,可以编辑Nginx配置文件。通常,Certbot会在/etc/nginx/sites-available/目录下创建一个符号链接到/etc/nginx/sites-enabled/目录。
例如,编辑你的站点配置文件:
sudo nano /etc/nginx/sites-available/yourdomain.com
确保配置文件包含以下内容:
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;
}
}
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/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;
}
}
保存并退出编辑器,然后测试Nginx配置:
sudo nginx -t
如果没有错误,重启Nginx服务:
sudo systemctl restart nginx
确保你的防火墙允许HTTP(80)和HTTPS(443)流量。如果你使用的是UFW(Uncomplicated Firewall),可以运行以下命令:
sudo ufw allow 'Nginx Full'
完成以上步骤后,你的LNMP环境应该已经成功配置了SSL。