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

非WWW站点robots.txt返回404错误,WWW版本正常如何修复?

解决WordPress非WWW域名下robots.txt 404且不触发重定向的问题

一、Apache服务器:调整.htaccess规则顺序

重定向规则必须放在WordPress默认规则之前,否则WordPress的Rewrite规则会优先处理请求,导致非WWW域名下的robots.txt直接返回404。

正确的.htaccess结构示例:

# 先执行WWW重定向
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
</IfModule>

# 再执行WordPress默认规则
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

替换为你的实际域名,并确保服务器已启用mod_rewrite模块

二、Nginx服务器:全局重定向配置

在Nginx的配置文件中,给非WWW域名设置全局重定向,确保所有请求(包括robots.txt)都被跳转:

# 处理HTTP非WWW请求
server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

# 处理HTTPS非WWW请求
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com;
    ssl_certificate /path/to/your/cert.pem;
    ssl_certificate_key /path/to/your/key.pem;
    return 301 https://www.example.com$request_uri;
}

配置后重启Nginx生效。

三、排查缓存干扰

  1. CDN缓存:手动清除Cloudflare、阿里云CDN等服务的全站缓存,重点删除robots.txt的缓存条目。
  2. 服务器缓存:关闭或清除Apachemod_cache、Nginxproxy_cache等服务器级缓存,或使用主机商提供的缓存清理工具。
  3. 本地缓存:用浏览器无痕模式访问非WWW域名的robots.txt,避免本地缓存影响测试结果。

四、WordPress functions.php 精准重定向

如果之前的functions.php写法无效,试试这个高优先级的钩子:

add_action('init', 'redirect_non_www_robots', 1);
function redirect_non_www_robots() {
    if (strpos($_SERVER['HTTP_HOST'], 'www') === false && $_SERVER['REQUEST_URI'] == '/robots.txt') {
        wp_redirect('https://www.example.com/robots.txt', 301);
        exit;
    }
}

将代码添加到当前主题的functions.php文件中,替换为你的实际域名

五、验证虚拟主机配置

确认主机商给非WWW和WWW域名设置的是同一个文档根目录,确保robots.txt文件存在于该根目录下(WWW版本正常说明文件本身没问题)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:22:16