大家好,今天我为大家带来一个简短的教程。我正在优化这个博客的SEO,想创建一个自动更新的网站地图。幸运的是,Spatie 为此创建了一个包。使用 spatie/laravel-sitemap,您可以自动化为您的Laravel应用程序创建网站地图的过程。让我们学习如何设置和使用这个包!
假设您已经设置了一个Laravel应用程序并运行了迁移。然后您可以通过运行以下命令安装 spatie/laravel-sitemap
包:
composer require spatie/laravel-sitemap
为了频繁更新网站地图,我们需要创建一个Artisan命令。在 App\Console\Commands
文件夹中创建一个 GenerateSitemap.php
文件。然后向该文件添加以下代码:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapGenerator;
class GenerateSitemap extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sitemap:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate the sitemap.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
SitemapGenerator::create(config('app.url'))
->writeToFile(public_path('sitemap.xml'));
}
}
此代码将为您的 .ENV
文件中指定的URL生成网站地图,并将生成的 sitemap.xml 文件放置在公开文件夹中。
然后将此命令安排在控制台内核中。为此,在 App\Console\Kernel.php
文件中插入以下代码:
protected function schedule(Schedule $schedule)
{
...
$schedule->command('sitemap:generate')->daily();
...
}
您需要确保您的服务器上正在运行调度器。我在我的服务器上通过添加以下cronjob来做了这个操作:
cd /var/www/vhosts/larapeak.com/github/larapeak.com && php artisan schedule:work >> /dev/null 2>&1
**注意**!cronjob在不同服务器上可能会有所不同。请参阅您的主机提供商的文档。
就这样!现在您有一个每天生成网站地图的脚本了!
如果您想保持同步并在我发布新文章时获得更新,请关注我的 Twitter!祝您有个愉快的一天。
jinas123, joedixon, isu3ru, mckenziearts, emmadonjo 这篇文章他们喜欢