alibaba258/laravel-robots
Manage robots.txt dynamically in Laravel. Build rules per environment (e.g., allow production with sitemap, disallow non-prod), generate plain-text output, and optionally persist configuration via migration with a swappable data source.
Installation:
composer require alibaba258/laravel-robots
Publish the config file (if needed):
php artisan vendor:publish --provider="Alibaba258\Robots\RobotsServiceProvider" --tag="config"
Basic Usage:
Generate a robots.txt file in your public directory:
use Alibaba258\Robots\Facades\Robots;
Robots::generate();
This creates a default robots.txt at /public/robots.txt.
First Use Case: Restrict a search engine (e.g., Google) from crawling a specific path:
Robots::disallow('Googlebot', '/admin');
Dynamic Rule Management: Use middleware to set rules per route:
public function handle($request, Closure $next) {
Robots::disallow('*', route('admin.dashboard'));
return $next($request);
}
Conditional Generation:
Generate robots.txt only in production:
if (app()->environment('production')) {
Robots::generate();
}
Custom Sitemaps: Add sitemaps dynamically:
Robots::addSitemap('https://example.com/sitemap.xml');
Cache Optimization:
Cache the generated robots.txt for performance:
Robots::generate()->cacheFor(3600); // Cache for 1 hour
Route-Based Rules:
Attach rules to specific routes in routes/web.php:
Route::get('/private', function () {
Robots::disallow('*', '/private');
return view('private');
});
User-Agent Groups: Apply rules to multiple user agents:
Robots::disallow(['Googlebot', 'Bingbot'], '/temp');
File Permissions:
Ensure the public/robots.txt file is writable by the web server. Use:
chmod 644 public/robots.txt
Overwriting Rules:
Rules are appended by default. Use clear() to reset before generating:
Robots::clear()->disallow('*', '/old-path')->generate();
Case Sensitivity:
User-agent names are case-sensitive (e.g., Googlebot ≠ googlebot).
Verify Output:
Check the generated robots.txt manually or via:
dd(Robots::getRules());
Logging:
Enable debug mode in config (debug=true) to log rule changes.
Custom Directives:
Extend the package by adding custom directives (e.g., Host):
Robots::addDirective('Host', 'example.com');
Event Listeners:
Listen for robots.generated events to post-process the file:
Robots::generated(function ($path) {
// Add custom logic (e.g., log, notify)
});
Configuration Overrides:
Override defaults in config/robots.php:
'default_user_agent' => 'Bingbot',
'file_path' => 'custom/robots.txt',
How can I help you explore Laravel packages today?