温馨提示×

centos laravel如何 HTTPS

小樊
46
2026-10-23 09:28:14
栏目: 智能运维

在 CentOS 上让 Laravel 支持 HTTPS,通常分为三步:
1️⃣ 申请/配置 SSL 证书
2️⃣ 配置 Web 服务器(Nginx 或 Apache)
3️⃣ Laravel 中强制 HTTPS(可选但推荐)

下面以 CentOS 7/8 + Nginx + Let’s Encrypt 为例说明。


一、申请 SSL 证书(Let’s Encrypt)

1. 安装 certbot

# CentOS 7
yum install epel-release -y
yum install certbot python2-certbot-nginx -y

# CentOS 8
dnf install certbot python3-certbot-nginx -y

2. 申请证书

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

替换 example.com 为你的域名
证书路径一般在:

/etc/letsencrypt/live/example.com/

二、Nginx 配置 HTTPS

示例 Nginx 配置

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

server {
    listen 443 ssl;
    server_name example.com www.example.com;

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

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

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

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

测试并重载

nginx -t
systemctl reload nginx

三、Laravel 中强制 HTTPS(推荐)

方法 1:中间件(最常用)

创建中间件:

php artisan make:middleware ForceHttps

编辑:

public function handle($request, Closure $next)
{
    if (!$request->secure()) {
        return redirect()->secure($request->getRequestUri());
    }
    return $next($request);
}

注册到 app/Http/Kernel.php:

protected $middleware = [
    \App\Http\Middleware\ForceHttps::class,
];

方法 2:.env 配置(简单)

APP_URL=https://example.com

并:

\URL::forceScheme('https');

(可放在 AppServiceProvider::boot())


四、自动续签证书

certbot renew --dry-run

加入定时任务:

crontab -e
0 3 * * * certbot renew --quiet

五、常见问题

✅ HTTPS 仍跳转 HTTP?
检查反向代理(如 CDN、Nginx)是否传 X-Forwarded-Proto

✅ 混合内容(Mixed Content)
Laravel 资源使用:

asset()
secure_asset()

如果你用的是 Apache / CentOS 6 / 宝塔 / Docker,可以告诉我,我可以给你对应方案。

0 踩