当我使用
secure_url()
或 asset()
时,它会链接到我网站的域 没有 “www”,即“example.com”。
如何将其更改为链接到“www.example.com”?
首先更改文件 config/app.php 中的应用程序 URL(或 .env 文件的 APP_URL 值):
'url' => 'http://www.example.com',
然后,让 URL 生成器使用它。将这些代码行添加到文件 app/Providers/AppServiceProvider.php 的 boot 方法中:
\URL::forceRootUrl(\Config::get('app.url'));
// And this if you wanna handle https URL scheme
// It's not usefull for http://www.example.com, it's just to make it more independant from the constant value
if (\Str::contains(\Config::get('app.url'), 'https://')) {
\URL::forceScheme('https');
//use \URL:forceSchema('https') if you use laravel < 5.4
}
使用较新版本的 Laravel(我已经使用 Laravel 11 对其进行了测试),这是完整的代码:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
URL::forceRootUrl(Config::get('app.url'));
if (Str::contains(Config::get('app.url'), 'https://')) {
URL::forceScheme('https');
}
}
}
这就是大家。
.env
文件更改
APP_URL='http://www.example.com'
config/app.php:
'url' => env('APP_URL', 'http://www.example.com')
在控制器或视图中使用配置方法调用
$url = config('app.url');
print_r($url);