目錄
2. Publish and Configure (Optional)
3. Generate the Sitemap
4. Better Approach: Use a Scheduled Command (Recommended)
a. Create an Artisan Command
b. Schedule the Command
c. Serve the Static File
5. Add Dynamic URLs (Optional)
Summary
首頁 php框架 Laravel 如何在Laravel應用程序中添加站點地圖?

如何在Laravel應用程序中添加站點地圖?

Jul 29, 2025 am 03:30 AM

安裝spatie/laravel-sitemap 包:通過Composer 安裝並引入spatie/laravel-sitemap 包以支持sitemap 生成功能;2. 可選配置:發布配置文件以自定義緩存、標籤或樣式設置;3. 創建路由生成sitemap:在web.php 中創建路由使用SitemapGenerator 生成並返回sitemap.xml;4. 推薦使用計劃任務:創建Artisan 命令並通過Laravel 調度器每日定時生成sitemap 以提升性能;5. 服務靜態文件:路由僅返回已生成的靜態sitemap.xml 文件避免重複生成;6. 添加動態URL:通過Sitemap::create() 手動添加如博客文章等動態內容並設置更新頻率、優先級等屬性;7. 提交至搜索引擎:將生成的sitemap.xml 提交至Google Search Console 和Bing Webmaster Tools 完成SEO 優化,最終實現Laravel 應用的高效、可維護的sitemap 集成。

How to add a sitemap to a Laravel application?

Adding a sitemap to a Laravel application is a straightforward process, especially if you're using a package like spatie/laravel-sitemap —which is the most popular and well-maintained solution. Here's how to do it step by step.

How to add a sitemap to a Laravel application?

1. Install the Spatie Sitemap Package

First, install the package via Composer:

 composer require spatie/laravel-sitemap

This package handles generating sitemaps, managing URLs, and even supports sitemap indexes for large sites.

How to add a sitemap to a Laravel application?

2. Publish and Configure (Optional)

You can publish the config file to customize behavior:

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

This creates config/sitemap.php . You usually don't need to change anything unless you want to customize cache settings, tags, or styling.

How to add a sitemap to a Laravel application?

3. Generate the Sitemap

Create a route in routes/web.php to generate and serve the sitemap:

 use Spatie\Sitemap\SitemapGenerator;

Route::get('/sitemap.xml', function () {
    // Generate the sitemap
    SitemapGenerator::create(config('app.url'))->writeToFile(public_path('sitemap.xml'));

    // Return the file
    return response()->file(public_path('sitemap.xml'));
});

⚠️ Note : This regenerates the sitemap on every request. That's fine for small or infrequently changing sites, but not ideal for large or high-traffic ones.


For production, generate the sitemap periodically using Laravel's task scheduler.

a. Create an Artisan Command

 php artisan make:command GenerateSitemap

Edit the new command in app/Console/Commands/GenerateSitemap.php :

 <?php

namespace App\Console\Commands;

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

class GenerateSitemap extends Command
{
    protected $signature = &#39;sitemap:generate&#39;;
    protected $description = &#39;Generate the sitemap&#39;;

    public function handle()
    {
        SitemapGenerator::create(config(&#39;app.url&#39;))
            ->writeToFile(public_path(&#39;sitemap.xml&#39;));

        $this->info(&#39;Sitemap generated successfully.&#39;);
    }
}

b. Schedule the Command

In app/Console/Kernel.php , add the command to the schedule:

 protected function schedule(Schedule $schedule)
{
    $schedule->command(&#39;sitemap:generate&#39;)->daily();
}

Now the sitemap will be regenerated once per day.

c. Serve the Static File

Update your route to just serve the static file without regenerating:

 Route::get(&#39;/sitemap.xml&#39;, function () {
    return response()->file(public_path(&#39;sitemap.xml&#39;));
});

Make sure the file exists. You can manually run the command once to create it:

 php artisan sitemap:generate

5. Add Dynamic URLs (Optional)

If you have dynamic content (eg, blog posts), you can manually add them:

 use Spatie\Sitemap\Sitemap;
use App\Models\Post;

Sitemap::create()
    ->add(&#39;/home&#39;)
    ->add(&#39;/about&#39;)
    ->add(&#39;/contact&#39;)
    ->add(
        Post::where(&#39;published&#39;, true)->get()
            ->map(function (Post $post) {
                return $post->toSitemapTag();
            })
    )
    ->writeToFile(public_path(&#39;sitemap.xml&#39;));

Make sure your model (eg, Post ) implements Spatie\Sitemap\Tags\Url or use ->add() with Url::create() :

 use Spatie\Sitemap\Tags\Url;

->add(Url::create("/blog/{$post->slug}")
    ->setLastModificationDate($post->updated_at)
    ->setChangeFrequency(&#39;weekly&#39;)
    ->setPriority(0.8))

6. Submit to Search Engines

Once your sitemap.xml is accessible (eg, https://yoursite.com/sitemap.xml ), submit it to:

  • Google Search Console
  • Bing Webmaster Tools

Summary

  • ✅ Use spatie/laravel-sitemap for easy integration
  • ✅ Generate sitemap via a scheduled command in production
  • ✅ Serve a static XML file for performance
  • ✅ Include dynamic content by manually adding URLs
  • ✅ Submit to search engines

That's it. Your Laravel app now has a working, SEO-friendly sitemap.

以上是如何在Laravel應用程序中添加站點地圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

Rimworld Odyssey溫度指南和Gravtech
1 個月前 By Jack chen
初學者的Rimworld指南:奧德賽
1 個月前 By Jack chen
PHP變量範圍解釋了
4 週前 By 百草
撰寫PHP評論的提示
3 週前 By 百草
在PHP中評論代碼
3 週前 By 百草

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1604
29
PHP教程
1509
276
選擇API身份驗證的Laravel Sanctum和Passport 選擇API身份驗證的Laravel Sanctum和Passport Jul 14, 2025 am 02:35 AM

LaravelSanctum適合簡單、輕量的API認證,如SPA或移動應用,而Passport適用於需要完整OAuth2功能的場景。 1.Sanctum提供基於令牌的認證,適合第一方客戶端;2.Passport支持授權碼、客戶端憑證等複雜流程,適合第三方開發者接入;3.Sanctum安裝配置更簡單,維護成本低;4.Passport功能全面但配置複雜,適合需要精細權限控制的平台。選擇時應根據項目需求判斷是否需要OAuth2特性。

Laravel中的配置緩存是什麼? Laravel中的配置緩存是什麼? Jul 27, 2025 am 03:54 AM

Laravel的配置緩存通過合併所有配置文件為一個緩存文件來提升性能。在生產環境中啟用配置緩存可減少每次請求時的I/O操作和文件解析,從而加快配置加載速度;1.應在部署應用、配置穩定且無需頻繁更改時啟用;2.啟用後修改配置需重新運行phpartisanconfig:cache才會生效;3.避免在配置文件中使用依賴運行時條件的動態邏輯或閉包;4.排查問題時應先清除緩存、檢查.env變量並重新緩存。

處理Laravel中的HTTP請求和響應。 處理Laravel中的HTTP請求和響應。 Jul 16, 2025 am 03:21 AM

在Laravel中處理HTTP請求和響應的核心在於掌握請求數據獲取、響應返回和文件上傳。 1.接收請求數據可通過類型提示注入Request實例並使用input()或魔術方法獲取字段,結合validate()或表單請求類進行驗證;2.返迴響應支持字符串、視圖、JSON、帶狀態碼和頭部的響應及重定向操作;3.處理文件上傳時需使用file()方法並結合store()存儲文件,上傳前應驗證文件類型和大小,存儲路徑可保存至數據庫。

在Laravel生成命名路線的URL。 在Laravel生成命名路線的URL。 Jul 16, 2025 am 02:50 AM

在Laravel中生成命名路由的URL最常用方法是使用route()輔助函數,它可根據路由名稱自動匹配路徑並處理參數綁定。 1.在控制器或視圖中傳入路由名稱和參數,如route('user.profile',['id'=>1]);2.多參數時也只需傳數組,順序不影響匹配,如route('user.post.show',['id'=>1,'postId'=>10]);3.在Blade模板中可直接嵌入鏈接,如查看資料;4.可選參數未提供時不顯示,如route('user.post',

如何在Laravel執行請求驗證? 如何在Laravel執行請求驗證? Jul 16, 2025 am 03:03 AM

在Laravel中進行請求驗證有兩種主要方法:控制器驗證和表單請求類。 1.控制器中使用validate()方法適合簡單場景,直接傳入規則並自動返回錯誤;2.使用FormRequest類適用於復雜或複用場景,通過Artisan創建類並在rules()中定義規則,實現代碼解耦與復用;3.可通過messages()自定義錯誤提示,提升用戶體驗;4.通過attributes()定義字段別名,使錯誤信息更友好;兩種方式各有優劣,應根據項目需求選擇合適方案。

了解Laravel Breeze和Jetstream之間的差異。 了解Laravel Breeze和Jetstream之間的差異。 Jul 15, 2025 am 12:43 AM

LaravelBreeze和Jetstream的主要區別在於定位和功能。 1.核心定位上,Breeze是輕量級認證腳手架,適合小型項目或自定義前端需求;Jetstream提供完整用戶系統,包含團隊管理、個人資料設置、API支持及雙因素驗證等功能,適合中大型應用。 2.前端技術棧方面,Breeze默認使用Blade Tailwind,偏向傳統服務端渲染;Jetstream支持Livewire或Inertia.js(結合Vue/React),更適合現代SPA架構。 3.安裝與定制上,Breeze更簡單易用

解釋Laravel雄辯的範圍。 解釋Laravel雄辯的範圍。 Jul 26, 2025 am 07:22 AM

Laravel的EloquentScopes是封裝常用查詢邏輯的工具,分為本地作用域和全局作用域。 1.本地作用域以scope開頭的方法定義,需顯式調用,如Post::published();2.全局作用域自動應用於所有查詢,常用於軟刪除或多租戶系統,需實現Scope接口並在模型中註冊;3.作用域可帶參數,如按年份或月份篩選文章,調用時傳入對應參數;4.使用時注意命名規範、鍊式調用、臨時禁用及組合擴展,提升代碼清晰度與復用性。

在Laravel中生成和使用數據庫工廠。 在Laravel中生成和使用數據庫工廠。 Jul 16, 2025 am 02:05 AM

數據庫工廠是Laravel中用於生成模型假數據的工具。它通過定義字段規則快速創建測試或開發所需的數據,例如使用phpartisanmake:factory生成工廠文件後,在definition()方法中設置如name、email等字段的生成邏輯,並通過User::factory()->create()創建記錄;1.支持批量生成數據,如User::factory(10)->create();2.可使用make()生成未存庫的數據數組;3.允許臨時覆蓋字段值;4.支持關聯關係,如自動創建

See all articles