Laravel项目HTTPS环境下Mixed Content请求被拦截问题求助
解决方案
Mixed Content错误的核心是HTTPS页面下发起了HTTP协议的异步请求,本质是Laravel识别当前请求协议为HTTP,生成的路由地址自动使用了HTTP前缀,可通过以下步骤修复:
一、调整.htaccess配置
在现有配置基础上新增HTTP强制跳转HTTPS规则,同时传递HTTPS协议标识给Laravel,避免应用误判请求协议,修改后的完整配置如下:
<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # 新增:强制所有HTTP请求跳转HTTPS RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # 新增:传递HTTPS协议头给应用,修复Laravel协议识别错误 RewriteCond %{HTTP:X-Forwarded-Proto} https RewriteRule .* - [E=HTTPS:on,E=SERVER_PORT:443] # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] # Disable Directory listing Options -Indexes # block files which needs to be hidden, specify .example extension of the file <Files ~ "\.(env|config.js|md|gitignore|gitattributes|lock)$"> Order allow,deny Deny from all </Files> </IfModule>
二、调整Laravel应用配置
- 修改项目根目录
.env文件,将APP_URL配置项的值改为https://开头的站点域名,示例:APP_URL=https://xxxxxx - 打开
app/Providers/AppServiceProvider.php,在boot方法中添加强制HTTPS生成路由、资源地址的配置:
public function boot() { // 生产环境强制使用HTTPS if (config('app.env') === 'production') { \URL::forceScheme('https'); } }
- 如果站点使用了CDN、负载均衡等代理服务,打开
app/Http/Middleware/TrustProxies.php,配置信任代理:
// 生产环境建议替换为实际代理IP段,避免安全问题 protected $proxies = '*'; protected $headers = \Illuminate\Http\Request::HEADER_X_FORWARDED_ALL;
三、生效验证
- 执行Laravel缓存清理命令:
php artisan config:clear && php artisan route:clear - 清理浏览器缓存(包含301重定向缓存)后重新访问页面,确认异步请求协议已变为HTTPS
内容的提问来源于stack exchange,提问作者KatiaSisHost
相关产品推荐
相关产品推荐

