isaacongoma/laravel-sitemap

轻松创建和生成网站地图

6.0.4 2021-05-27 07:28 UTC

README

Latest Version on Packagist Software License Test Status Code Style Status Total Downloads

此包可以在不手动添加 URL 的情况下生成网站地图。它通过爬取您整个网站来实现。

use Spatie\Sitemap\SitemapGenerator;

SitemapGenerator::create('https://example.com')->writeToFile($path);

您也可以手动创建您的网站地图

use Carbon\Carbon;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

Sitemap::create()

    ->add(Url::create('/home')
        ->setLastModificationDate(Carbon::yesterday())
        ->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY)
        ->setPriority(0.1))

   ->add(...)

   ->writeToFile($path);

或者,您可以通过先生成网站地图然后添加更多链接来兼得两者之优

SitemapGenerator::create('https://example.com')
   ->getSitemap()
   ->add(Url::create('/extra-page')
        ->setLastModificationDate(Carbon::yesterday())
        ->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY)
        ->setPriority(0.1))

    ->add(...)

    ->writeToFile($path);

您还可以控制网站地图的最大深度

SitemapGenerator::create('https://example.com')
    ->configureCrawler(function (Crawler $crawler) {
        $crawler->setMaximumDepth(3);
    })
    ->writeToFile($path);

生成器具有在每个页面上执行 JavaScript 的能力 (查看文档),因此通过 JavaScript 注入 DOM 的链接也会被爬取。

您还可以使用您可用的文件系统磁盘之一来写入网站地图。

SitemapGenerator::create('https://example.com')->getSitemap()->writeToDisk('public', 'sitemap.xml');

您还可以通过实现 \Spatie\Sitemap\Contracts\Sitemapable 接口直接添加您的模型。

use Spatie\Sitemap\Contracts\Sitemapable;
use Spatie\Sitemap\Tags\Url;

class Post extends Model implements Sitemapable
{
    public function toSitemapTag(): Url | string | array
    {
        return route('blog.post.show', $this);
    }
}

现在您可以向网站地图添加单个帖子模型,甚至整个集合。

use Spatie\Sitemap\Sitemap;

Sitemap::create()
    ->add($post)
    ->add(Post::all());

这样,您可以快速添加所有页面,而无需爬取它们。

支持我们

我们在创建 最佳类别的开源包 上投入了大量资源。您可以通过 购买我们的付费产品之一 来支持我们。

我们非常感谢您从您的家乡寄给我们明信片,说明您正在使用我们的哪个包。您可以在 我们的联系页面 上找到我们的地址。我们在 我们的虚拟明信片墙 上发布所有收到的明信片。

安装

首先,使用 composer 安装包

composer require spatie/laravel-sitemap

该包将自动注册自身。

如果您想自动和频繁地更新您的网站地图,您需要执行 一些额外步骤

配置

您可以通过发布配置来覆盖爬虫的默认选项。首先发布配置

php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=config

这会将默认配置复制到 config/sitemap.php,您可以在那里编辑它。

use GuzzleHttp\RequestOptions;
use Spatie\Sitemap\Crawler\Profile;

return [

    /*
     * These options will be passed to GuzzleHttp\Client when it is created.
     * For in-depth information on all options see the Guzzle docs:
     *
     * http://docs.guzzlephp.org/en/stable/request-options.html
     */
    'guzzle_options' => [

        /*
         * Whether or not cookies are used in a request.
         */
        RequestOptions::COOKIES => true,

        /*
         * The number of seconds to wait while trying to connect to a server.
         * Use 0 to wait indefinitely.
         */
        RequestOptions::CONNECT_TIMEOUT => 10,

        /*
         * The timeout of the request in seconds. Use 0 to wait indefinitely.
         */
        RequestOptions::TIMEOUT => 10,

        /*
         * Describes the redirect behavior of a request.
         */
        RequestOptions::ALLOW_REDIRECTS => false,
    ],
    
    /*
     * The sitemap generator can execute JavaScript on each page so it will
     * discover links that are generated by your JS scripts. This feature
     * is powered by headless Chrome.
     */
    'execute_javascript' => false,
    
    /*
     * The package will make an educated guess as to where Google Chrome is installed. 
     * You can also manually pass it's location here.
     */
    'chrome_binary_path' => '',

    /*
     * The sitemap generator uses a CrawlProfile implementation to determine
     * which urls should be crawled for the sitemap.
     */
    'crawl_profile' => Profile::class,
    
];

使用

生成网站地图

最简单的方法是爬取给定的域名并生成包含所有找到的链接的网站地图。网站地图的目标应由 $path 指定。

SitemapGenerator::create('https://example.com')->writeToFile($path);

生成的网站地图将类似于以下内容

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://example.com</loc>
        <lastmod>2016-01-01T00:00:00+00:00</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc>https://example.com/page</loc>
        <lastmod>2016-01-01T00:00:00+00:00</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>

    ...
</urlset>

自定义网站地图生成器

定义自定义爬取配置文件

您可以通过实现 Spatie\Crawler\CrawlProfiles\CrawlProfile 接口并自定义 shouldCrawl() 方法来创建自定义爬取配置文件,以完全控制应爬取哪些 URL/域名/子域名。

use Spatie\Crawler\CrawlProfiles\CrawlProfile;
use Psr\Http\Message\UriInterface;

class CustomCrawlProfile extends CrawlProfile
{
    public function shouldCrawl(UriInterface $url): bool
    {
        if ($url->getHost() !== 'localhost') {
            return false;
        }
        
        return $url->getPath() === '/';
    }
}

并在 config/sitemap.php 中注册您的 CustomCrawlProfile::class

return [
    ...
    /*
     * The sitemap generator uses a CrawlProfile implementation to determine
     * which urls should be crawled for the sitemap.
     */
    'crawl_profile' => CustomCrawlProfile::class,
    
];

更改属性

要更改联系页面的 lastmodchangefreqpriority 属性

use Carbon\Carbon;
use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;

SitemapGenerator::create('https://example.com')
   ->hasCrawled(function (Url $url) {
       if ($url->segment(1) === 'contact') {
           $url->setPriority(0.9)
               ->setLastModificationDate(Carbon::create('2016', '1', '1'));
       }

       return $url;
   })
   ->writeToFile($sitemapPath);

省略某些链接

如果您不希望在网站地图中显示被爬取的链接,只需在传递给 hasCrawled 的可调用函数中不返回它即可。

use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;

SitemapGenerator::create('https://example.com')
   ->hasCrawled(function (Url $url) {
       if ($url->segment(1) === 'contact') {
           return;
       }

       return $url;
   })
   ->writeToFile($sitemapPath);

防止爬虫爬取某些页面

您还可以通过传递一个 callableshouldCrawl 来指示底层爬虫不要爬取某些页面。

注意: shouldCrawl 只与默认爬取 Profile 或实现 shouldCrawlCallback 方法的自定义爬取配置文件一起使用。

use Spatie\Sitemap\SitemapGenerator;
use Psr\Http\Message\UriInterface;

SitemapGenerator::create('https://example.com')
   ->shouldCrawl(function (UriInterface $url) {
       // All pages will be crawled, except the contact page.
       // Links present on the contact page won't be added to the
       // sitemap unless they are present on a crawlable page.
       
       return strpos($url->getPath(), '/contact') === false;
   })
   ->writeToFile($sitemapPath);

配置爬虫

爬虫本身可以被配置以执行一些不同的事情。

您可以为地图生成器使用的爬虫进行配置,例如:忽略机器人检查;如下所示。

SitemapGenerator::create('https://:4020')
    ->configureCrawler(function (Crawler $crawler) {
        $crawler->ignoreRobots();
    })
    ->writeToFile($file);

限制爬取页面的数量

您可以通过调用setMaximumCrawlCount来限制爬取页面的数量

use Spatie\Sitemap\SitemapGenerator;

SitemapGenerator::create('https://example.com')
    ->setMaximumCrawlCount(500) // only the 500 first pages will be crawled
    ...

执行JavaScript

地图生成器可以在每个页面上执行JavaScript,以便发现由您的JS脚本生成的链接。您可以通过在配置文件中将execute_javascript设置为true来启用此功能。

在底层,使用无头Chrome来执行JavaScript。以下是关于如何在您的系统上安装它的指南

该包将对您的系统上Chrome的安装位置做出明智的猜测。您也可以手动将Chrome二进制文件的路径传递给executeJavaScript()

手动添加链接

您可以为地图手动添加链接

use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;

SitemapGenerator::create('https://example.com')
    ->getSitemap()
    // here we add one extra link, but you can add as many as you'd like
    ->add(Url::create('/extra-page')->setPriority(0.5))
    ->writeToFile($sitemapPath);

为链接添加替代版本

多语言网站可能有几个相同页面的替代版本(每种语言一个)。基于前面的示例,添加替代版本可以如下进行

use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;

SitemapGenerator::create('https://example.com')
    ->getSitemap()
    // here we add one extra link, but you can add as many as you'd like
    ->add(Url::create('/extra-page')->setPriority(0.5)->addAlternate('/extra-pagina', 'nl'))
    ->writeToFile($sitemapPath);

注意addAlternate函数,它接受一个替代URL及其所属的区域设置。

手动创建地图

您也可以完全手动创建地图

use Carbon\Carbon;

Sitemap::create()
   ->add('/page1')
   ->add('/page2')
   ->add(Url::create('/page3')->setLastModificationDate(Carbon::create('2016', '1', '1')))
   ->writeToFile($sitemapPath);

创建地图索引

您可以创建一个地图索引

use Spatie\Sitemap\SitemapIndex;

SitemapIndex::create()
    ->add('/pages_sitemap.xml')
    ->add('/posts_sitemap.xml')
    ->writeToFile($sitemapIndexPath);

您可以将一个Spatie\Sitemap\Tags\Sitemap对象传递给手动设置lastModificationDate属性。

use Spatie\Sitemap\SitemapIndex;
use Spatie\Sitemap\Tags\Sitemap;

SitemapIndex::create()
    ->add('/pages_sitemap.xml')
    ->add(Sitemap::create('/posts_sitemap.xml')
        ->setLastModificationDate(Carbon::yesterday()))
    ->writeToFile($sitemapIndexPath);

生成的地图索引看起来类似于以下这样

<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <sitemap>
      <loc>http://www.example.com/pages_sitemap.xml</loc>
      <lastmod>2016-01-01T00:00:00+00:00</lastmod>
   </sitemap>
   <sitemap>
      <loc>http://www.example.com/posts_sitemap.xml</loc>
      <lastmod>2015-12-31T00:00:00+00:00</lastmod>
   </sitemap>
</sitemapindex>

创建包含后续地图的地图索引

您可以通过调用maxTagsPerSitemap方法生成一个只包含给定数量标签的地图

use Spatie\Sitemap\SitemapGenerator;

SitemapGenerator::create('https://example.com')
    ->maxTagsPerSitemap(20000)
    ->writeToFile(public_path('sitemap.xml'));

频繁生成地图

您的网站可能需要不时进行更新。为了使您的地图反映这些更改,您可以定期运行生成器。最简单的方法是利用Laravel的默认调度功能。

您可以设置一个类似于以下这样的艺术家的命令

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapGenerator;

class GenerateSitemap extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $signature = 'sitemap:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate the sitemap.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // modify this to your own needs
        SitemapGenerator::create(config('app.url'))
            ->writeToFile(public_path('sitemap.xml'));
    }
}

然后应在控制台内核中安排该命令。

// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    ...
    $schedule->command('sitemap:generate')->daily();
    ...
}

变更日志

有关最近更改的更多信息,请参阅变更日志

测试

首先在单独的终端会话中启动测试服务器

cd tests/server
./start_server.sh

服务器运行时,您可以执行测试

$ composer test

贡献

有关详细信息,请参阅贡献指南

安全

如果您发现任何安全问题,请通过电子邮件freek@spatie.be联系,而不是使用问题跟踪器。

鸣谢

支持我们

Spatie是一家位于比利时安特卫普的网页设计公司。您可以在我们的网站上找到我们所有开源项目的概述在此处

您的业务依赖于我们的贡献吗?在Patreon上与我们联系并支持我们。所有承诺都将专门用于分配人员以维护和新奇事物。

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件