首页 > 解决方案 > 如何为不存在的 WordPress http 页面返回 404 而不是 301 然后 404

问题描述

有人创建了数千个指向我网站不存在页面的反向链接。不幸的是,Googlebot 试图抓取这些页面。我的网站在 HTTPs 中。Googlebot 访问页面的 HTTP 版本,我的服务器首先返回 301 重定向,然后在第二个 Googlebot 查询时返回 404。它会大大减慢爬行速度。事实上,现在,Googlebot 看到 301 并决定不立即遵循重定向。

我想知道是否可以通过在 Htaccess 文件中添加指令来在返回 301 之前返回 404。同时,当 Google 尝试访问现有 WordPress 页面的 HTTP 版本时,我希望服务器返回 301 重定向到 HTTPS。

示例:因此,HTTP ://example.com/jdfjdfd/ 不存在。Googlebot 访问它并返回 301,然后我的服务器在 Googlebot 访问 HTTPS://example.com/jdfjdfd/ 时返回 404 我希望我的服务器在 Googlebot 访问 HTTP://example.com/ 时返回 404 错误页面jdfjdfd/

我尝试在 WordPress 指令之后添加重定向指令,但它不起作用:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTPS} off
rewriterule ^(.*)$ https://example.com/$1 [R=301,L]

但它不起作用。

也许它只能在 PHP 中使用与此类似的东西并在 functions.php 中进行修改来完成?

// add_action('template_redirect', 'redirect_core', 5000);
// add_action('init', 'redirect_core', 5000);
// add_action('wp_loaded', 'redirect_core', 5000);
function redirect_core(){
  if (!is_ssl() ) {
    wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301);
    exit();
  }
}

标签: phpwordpress.htaccessredirect

解决方案


根据您显示的示例,您能否尝试以下操作。请在测试您的 URL 之前清除浏览器缓存。

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

RewriteCond %{HTTPS} off
Rewriterule ^ https://example.com%{REQUEST_URI} [R=301,L,NE]
    
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

始终建议保留在顶部应用 https 的规则。


推荐阅读