linux

LNMP架构中Nginx如何配置SSL证书

小樊
50
2025-06-12 21:03:37
栏目: 云计算

在LNMP(Linux, Nginx, MySQL, PHP)架构中,配置Nginx以使用SSL证书可以确保通过HTTPS协议传输的数据是加密的。以下是配置Nginx以使用SSL证书的步骤:

  1. 获取SSL证书

    • 你可以从Let’s Encrypt免费获取SSL证书。
    • 或者,如果你有购买证书,可以从你的证书颁发机构(CA)获取。
  2. 安装Nginx(如果尚未安装):

    sudo apt update
    sudo apt install nginx
    
  3. 配置Nginx以使用SSL证书

    • 打开Nginx配置文件,通常位于/etc/nginx/sites-available/目录下。你可以创建一个新的配置文件或编辑默认的配置文件。
    sudo nano /etc/nginx/sites-available/default
    
    • server块中添加或修改以下内容:
    server {
        listen 443 ssl;
        server_name yourdomain.com www.yourdomain.com;
    
        ssl_certificate /path/to/your/fullchain.pem;
        ssl_certificate_key /path/to/your/privkey.pem;
    
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
        ssl_prefer_server_ciphers on;
    
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
    
        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;
        }
    }
    
    server {
        listen 80;
        server_name yourdomain.com www.yourdomain.com;
    
        location / {
            return 301 https://$host$request_uri;
        }
    }
    
    • 确保将yourdomain.com替换为你的实际域名,并将/path/to/your/fullchain.pem/path/to/your/privkey.pem替换为你的SSL证书和私钥的实际路径。
  4. 测试Nginx配置

    sudo nginx -t
    
  5. 重新加载Nginx

    sudo systemctl reload nginx
    
  6. 验证SSL配置

    • 使用浏览器访问你的域名,确保浏览器显示安全连接(通常显示为锁形图标)。
    • 你可以使用SSL检查工具(如SSL Labs)来验证你的SSL配置是否正确。

通过以上步骤,你应该能够成功配置Nginx以使用SSL证书,从而确保你的网站通过HTTPS协议提供服务。

0
看了该问题的人还看了