SilverStripe 3.5.1:未生成AMP链接时禁止访问amp.html版本
Got it, let's tackle this problem step by step. You already have logic in place to skip generating AMP links when either AmpImage or AmpContent is empty—now we need to block direct access to /amp.html URLs for pages that don't qualify. Here's how to implement this in your SilverStripe AMP module branch:
1. Override the AMP Controller
First, we'll extend the module's core AMP controller to add access checks. Create a custom controller in your project (or your forked module) that inherits from the module's base controller:
<?php namespace YourProject\AMP; use SilverStripe\Control\HTTPResponse_Exception; use TheZenMonkey\AMP\Controllers\AMPController as BaseAMPController; class AMPController extends BaseAMPController { public function init() { parent::init(); $currentPage = $this->getCurrentPage(); // Reuse your existing validation logic for AMP eligibility $isAmpEligible = $currentPage->AmpImage()->exists() && !empty($currentPage->AmpContent); if (!$isAmpEligible) { // Return 404 to indicate the AMP version doesn't exist throw new HTTPResponse_Exception('AMP version not available for this page', 404); // Alternatively, redirect to the regular page (choose based on your SEO needs) // return $this->redirect($currentPage->Link(), 301); } } }
2. Update Routing to Use Your Custom Controller
Next, tell SilverStripe to use your new controller for AMP requests instead of the module's default one. Add this to your project's config.yml:
SilverStripe\Control\Director: rules: '$URLSegment/amp.html': 'YourProject\AMP\AMPController'
3. Verify Consistency with Existing Logic
Since you already have logic that skips adding AMP links to pages without AmpImage or AmpContent, this server-side check ensures alignment:
- Users can't stumble on AMP pages via direct URL entry if they shouldn't exist
- Search engines will respect the 404 status code (or 301 redirect) and won't index invalid AMP pages
- Your front-end link generation and back-end access control stay in sync
This approach is clean, reuses your existing validation logic, and adheres to best practices for handling unavailable content.
内容的提问来源于stack exchange,提问作者Dejsa Cocan

