You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10.32.1中url()方法随机返回http与https的问题求助

Laravel url()方法仅在src/href返回HTTPS的解决办法

问题现象

Laravel 10.32.1环境下,网站已启用HTTPS,.env中APP_URL配置为HTTPS,但url()方法仅在<img>的src、<a>的href这类属性内返回HTTPS链接,注释、自定义data属性等场景均生成HTTP链接,示例代码与生成结果如下:

代码示例

<!--
{{ url('signin/oauth/google/a.png') }}
{{ url('signin/oauth/google') }}
{{ url('assets/img/logo.png') }}
{{ env('APP_URL') }}
-->
<img src="{{url('assets/img/logo.png')}}" class="d-none" />
<div id="g_id_onload"
data-client_id="<?=env('GOOGLE_CLIENT_ID')?>"
data-login_uri="<?= url('signin/oauth/google') . $intent->getParams() ?>"
data-auto_prompt="false">

生成的HTML

<!--
http://auth.example.com/signin/oauth/google/a.png
http://auth.example.com/signin/oauth/google
http://auth.example.com/assets/img/logo.png
https://auth.example.com
-->
<img src="https://auth.example.com/assets/img/logo.png" class="d-none" />
<div id="g_id_onload"
data-client_id="MY_CLIENT_ID"
data-login_uri="http://auth.example.com/signin/oauth/google?"
data-auto_prompt="false">
</div>

解决步骤

1. 强制全局使用HTTPS链接

在app/Providers/AppServiceProvider.php的boot方法中添加代码,强制Laravel生成HTTPS链接:

use Illuminate\Support\Facades\URL;

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

注:若本地环境也需强制HTTPS,直接移除if判断即可。

2. 清除配置与视图缓存

执行以下命令确保配置修改生效:

php artisan config:cache
php artisan view:cache

3. 检查反向代理服务器配置(如Nginx)

若网站通过Nginx等反向代理提供服务,需在Nginx配置中添加HTTPS协议头传递:

proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;

同时在config/trustedproxy.php中添加代理服务器IP到受信任列表,确保Laravel正确识别HTTPS请求:

return [
    'proxies' => [
        '127.0.0.1', // 替换为你的代理服务器实际IP
        // 其他需信任的IP地址
    ],
    // 保留其他默认配置
];

内容的提问来源于stack exchange,提问作者Hajime Saki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 09:42:36