温馨提示×

Laravel如何在Linux上配置SSL证书

小樊
40
2026-01-02 23:56:32
栏目: 云计算

在Linux上为Laravel应用程序配置SSL证书,通常需要以下几个步骤:

1. 获取SSL证书

你可以从Let’s Encrypt免费获取SSL证书。使用Certbot是一个常见的方法。

安装Certbot

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

获取证书

假设你的域名是example.com,运行以下命令:

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

按照提示完成证书的获取和配置。

2. 配置Nginx

Certbot会自动修改你的Nginx配置文件,通常位于/etc/nginx/sites-available/example.com

示例配置

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

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

    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/example.com;
    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/ /index.php?$query_string;
    }
}

3. 重启Nginx

sudo systemctl restart nginx

4. 配置Laravel

确保Laravel的.env文件中设置了正确的URL:

APP_URL=https://example.com

5. 测试配置

访问你的域名,确保SSL证书正确安装并且网站可以正常访问。

6. 自动续期

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

sudo certbot renew --dry-run

如果一切正常,Certbot会自动续期并更新Nginx配置文件中的证书路径。

通过以上步骤,你应该能够在Linux上成功为Laravel应用程序配置SSL证书。

0