在 CentOS 上让 Laravel 支持 HTTPS,通常分为三步:
1️⃣ 申请/配置 SSL 证书
2️⃣ 配置 Web 服务器(Nginx 或 Apache)
3️⃣ Laravel 中强制 HTTPS(可选但推荐)
下面以 CentOS 7/8 + Nginx + Let’s Encrypt 为例说明。
# CentOS 7
yum install epel-release -y
yum install certbot python2-certbot-nginx -y
# CentOS 8
dnf install certbot python3-certbot-nginx -y
certbot --nginx -d example.com -d www.example.com
替换
example.com为你的域名
证书路径一般在:
/etc/letsencrypt/live/example.com/
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
创建中间件:
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,
];
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,可以告诉我,我可以给你对应方案。