You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress页面访问控制:仅允许站内锚点访问,URL直连返回404

WordPress实现站内锚点可访问、直接输URL返回404的方案

核心逻辑

通过验证请求来源区分两种访问场景:站内锚点跳转时,请求带有本站Referer或自定义验证标记;直接地址栏访问时无有效验证信息,触发404。


方案一:PHP后端验证(推荐,安全性高)

利用WordPress的template_redirect钩子在页面加载前完成验证,确保拦截逻辑无法被前端绕过。

步骤1:在主题functions.php添加验证代码

add_action('template_redirect', 'restrict_direct_page_access');
function restrict_direct_page_access() {
    // 替换为你需要限制的页面slug(多个页面可用数组:['page', 'secret-page'])
    $restricted_slugs = 'page';
    
    if (is_page($restricted_slugs)) {
        $site_domain = home_url();
        // 验证来源是否为本站
        $valid_referer = isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], $site_domain) !== false;
        // 验证自定义URL参数(应对浏览器禁用Referer的情况)
        $valid_token = isset($_GET['internal_access']) && $_GET['internal_access'] === 'true';
        
        if (!$valid_referer && !$valid_token) {
            // 触发404状态并加载404模板
            global $wp_query;
            $wp_query->set_404();
            status_header(404);
            get_template_part('404');
            exit;
        }
    }
}

步骤2:修改站内锚点链接

给链接加上自定义验证参数,确保跳转时能通过后端校验:

<a href="<?php echo get_permalink(get_page_by_path('page')); ?>?internal_access=true">Go to Page</a>

方案二:JS前端控制(适合快速测试,安全性较弱)

通过前端JS判断请求来源,切换显示404或页面内容,缺点是用户可通过修改前端代码绕过限制。

目标页面模板代码

<body>
    <div class="404" id="404-container">Nothing was found at this location.</div>
    <div class="content" id="page-content" style="display: none;">Page Content</div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const siteOrigin = window.location.origin;
            const hasValidReferrer = document.referrer.includes(siteOrigin);
            const hasValidToken = new URLSearchParams(window.location.search).get('internal_access') === 'true';
            
            if (hasValidReferrer || hasValidToken) {
                document.getElementById('404-container').style.display = 'none';
                document.getElementById('page-content').style.display = 'block';
            }
        });
    </script>
</body>

站内锚点链接修改

同样需要加上验证参数:

<a href="example.com/page/?internal_access=true">Go to Page</a>

关键注意事项

  • Referer兼容性:部分浏览器隐私设置会禁用Referer,必须配合URL参数作为兜底验证,避免误拦截合法的站内跳转。
  • 后端优先:后端方案是唯一可靠的限制方式,前端方案仅适合临时场景或非敏感页面。
  • 多页面适配:如果需要限制多个页面,只需将$restricted_slugs改为数组格式即可。

内容的提问来源于stack exchange,提问作者moises gomez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 05:25:38