温馨提示×

linux laravel怎样部署ssl

小樊
34
2026-10-12 23:41:48
栏目: 云计算

在 Linux + Laravel 环境下部署 SSL,通常分为 申请证书 和 Web 服务器配置 两部分。下面以最常见的 Nginx + Let’s Encrypt(免费 SSL) 为例说明,也会补充 Apache 方式。


一、准备工作

  1. 一台 Linux 服务器(CentOS / Ubuntu 等)
  2. 已安装:
    • Nginx 或 Apache
    • PHP + Laravel 可正常运行
  3. 域名已解析到服务器 IP
  4. 确保 80 和 443 端口开放

二、使用 Let’s Encrypt 免费 SSL(推荐)

1️⃣ 安装 Certbot

Ubuntu / Debian

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

CentOS

sudo yum install epel-release -y
sudo yum install certbot python3-certbot-nginx -y

2️⃣ 自动申请并配置 SSL(Nginx)

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

按提示输入邮箱、同意协议
✅ Certbot 会自动:

  • 申请证书
  • 修改 Nginx 配置
  • 开启 HTTPS

3️⃣ 测试自动续期

sudo certbot renew --dry-run

Let’s Encrypt 证书 90 天 有效期,Certbot 会自动续期。


三、Nginx 手动配置 SSL(已有证书)

如果你已有 .crt 和 .key 文件:

Nginx 配置示例

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com/fullchain.crt;
    ssl_certificate_key /etc/ssl/example.com/private.key;

    root /var/www/laravel/public;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

重启 Nginx:

sudo systemctl restart nginx

四、Apache 部署 SSL(简要)

启用模块

sudo a2enmod ssl
sudo a2ensite default-ssl

修改配置

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/laravel/public

    SSLEngine on
    SSLCertificateFile /path/fullchain.crt
    SSLCertificateKeyFile /path/private.key
</VirtualHost>
sudo systemctl restart apache2

五、Laravel 相关配置

1️⃣ 设置 APP_URL

.env

APP_URL=https://example.com

2️⃣ 强制 HTTPS(可选)

App/Providers/AppServiceProvider.php

public function boot()
{
    if (env('APP_ENV') === 'production') {
        \URL::forceScheme('https');
    }
}

六、常见问题

✅ mixed content 错误
→ 静态资源使用 asset() 或 secure_asset()

✅ 证书不生效
→ 检查防火墙、域名解析、Nginx 配置

✅ 本地开发
→ 可用 mkcert 或 laravel valet


如果你用的是 具体发行版(Ubuntu/CentOS)或面板(宝塔/1Panel),可以告诉我,我可以给你更精确的部署步骤。

0 踩