在LNMP(Linux, Nginx, MySQL, PHP)架构中,配置Nginx以支持HTTPS涉及几个步骤。以下是一个基本的指南:
首先,你需要一个SSL证书。你可以从Let’s Encrypt免费获取,或者购买一个商业证书。
你可以使用Certbot来自动获取和续订Let’s Encrypt证书。以下是基本步骤:
sudo apt update
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按照提示完成证书的获取和配置。
编辑Nginx配置文件,通常位于/etc/nginx/sites-available/yourdomain.com
。如果你使用的是Certbot,它会自动创建一个符号链接到sites-enabled
目录。
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
location /.well-known/acme-challenge/ {
root /var/www/letsencrypt;
}
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版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location / {
try_files $uri $uri/ =404;
}
}
在重新加载Nginx之前,测试配置文件是否有语法错误:
sudo nginx -t
如果没有错误,重新加载Nginx以应用更改:
sudo systemctl reload nginx
打开浏览器,访问https://yourdomain.com
,确保页面正确显示并且没有安全警告。
Certbot会自动设置一个cron作业来定期续订证书。你也可以手动测试续订过程:
sudo certbot renew --dry-run
如果没有错误,证书将会被续订并且Nginx配置会自动更新。
通过以上步骤,你应该能够在LNMP架构中成功配置Nginx以支持HTTPS。