Add this line to your routes.php
Route::get('/sitemap', function()
{
return Response::view('sitemap')->header('Content-Type', 'application/xml');
});
Create new file appHttpMiddlewaresitemap.php
<?php namespace AppHttpMiddleware;
use Closure;
use CarbonCarbon;
use IlluminateContractsAuthGuard;
class sitemap {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if ( !$request->is("sitemap") && $request->fullUrl() != '' && $this->auth->guest() )
{
$aSiteMap = Cache::get('sitemap', []);
$changefreq = 'always';
if ( !empty( $aSiteMap[$request->fullUrl()]['added'] ) ) {
$aDateDiff = Carbon::createFromTimestamp( $aSiteMap[$request->fullUrl()]['added'] )->diff( Carbon::now() );
if ( $aDateDiff->y > 0 ) {
$changefreq = 'yearly';
} else if ( $aDateDiff->m > 0) {
$changefreq = 'monthly';
} else if ( $aDateDiff->d > 6 ) {
$changefreq = 'weekly';
} else if ( $aDateDiff->d > 0 && $aDateDiff->d < 7 ) {
$changefreq = 'daily';
} else if ( $aDateDiff->h > 0 ) {
$changefreq = 'hourly';
} else {
$changefreq = 'always';
}
}
$aSiteMap[$request->fullUrl()] = [
'added' => time(),
'lastmod' => Carbon::now()->toIso8601String(),
'priority' => 1 - substr_count($request->getPathInfo(), '/') / 10,
'changefreq' => $changefreq
];
Cache::put('sitemap', $aSiteMap, 2880);
}
return $next($request);
}
}
And create new view file resourcesviewssitemap.blade.php
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
@foreach( Cache::get('sitemap') as $url => $params )
<url>
<loc>{{$url}}</loc>
<lastmod>{{$params['lastmod']}}</lastmod>
<changefreq>{{$params['changefreq']}}</changefreq>
<priority>{{$params['priority']}}</priority>
</url>
@endforeach
</urlset>
Add an entry to protected $middleware array in the file appHttpKernel.php
'sitemap' => 'AppHttpMiddlewaresitemap'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…