nginx 的 error_page 404 不支持变量(如 $uri),直接写 http 地址会导致字面量跳转失效;应改用 @named-location + return 302 动态拼接搜狗(query=)或百度(wd=)搜索 url,或交由 php 处理并 urlencode 路径。

直接跳转到搜狗或百度搜索不是“错误处理”,而是主动的用户引导行为;Nginx 的 error_page 404 本身不支持动态拼接搜索 URL(比如把请求路径变成搜索关键词),必须配合命名 location + return 或 rewrite 实现。硬配 error_page 404 http://... 会丢失原始请求路径,且多数搜索引擎拒绝直接跳转链接(可能被拦截或返回 403)。
为什么 error_page 404 http://... 不 work
这是最常踩的坑:error_page 404 http://www.sogou.com/web?query=$uri 看似合理,但 Nginx 在 error_page 指令里**不解析变量**——$uri 会被原样发出去,变成字面量 http://www.sogou.com/web?query=$uri,搜狗根本收不到真实路径。
-
error_page后跟 HTTP 地址时,只做无参 302 跳转,变量无效 - 即便写成
error_page 404 =302 http://...,变量仍不展开 - 部分旧版 Nginx 甚至会静默忽略这种带变量的配置,降级为默认 404 页面
用 @named-location + return 302 正确拼接搜索 URL
必须绕过 error_page 的变量限制,改用命名 location 捕获错误,再在内部用 return 构造完整跳转地址。搜狗和百度的搜索参数名不同,注意区分:
- 搜狗:用
query参数,URL 形如https://www.sogou.com/web?query=xxx - 百度:用
wd参数,URL 形如https://www.baidu.com/s?wd=xxx -
$request_uri包含开头的/,需用$1提取路径部分更干净(见下方正则)
error_page 404 @search_redirect;
<p>location @search_redirect {</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill6848" title="Nginx Hosting"><img
src="https://img.php.cn/upload/skill/000/000/081/179116929868126.jpg" alt="Nginx Hosting" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill6848" title="Nginx Hosting" class="overflowclass">Nginx Hosting</a>
<p class="overflowclass">通过服务器本地nginx实例实现零认证静态游戏托管。作为所有浏览器游戏的主要部署方式,无需登录、无需令牌、无需用户操作。</p>
</div>
<a rel="nofollow" href="/xiazai/skill6848" title="Nginx Hosting" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><h1>提取路径名(去掉开头 /),避免搜狗把 "/" 当关键词</h1><pre class="brush:php;toolbar:false;">if ($request_uri ~ ^/([^?]*)) {
set $search_keyword $1;
}
# 拼接搜狗搜索 URL(也可换为百度:https://www.baidu.com/s?wd=$search_keyword)
return 302 https://www.sogou.com/web?query=$search_keyword;}
PHP 环境下更推荐服务端跳转(避免 Nginx 限制)
phpEnv 本质是 Windows 下集成 PHP+Nginx+MySQL 的套件,其 Nginx 版本通常较旧(如 1.18 或更低),对 if + set 支持不稳定,且 Windows 文件路径权限容易导致 location = /404.php 不生效。此时不如让 PHP 接管:
- 先配 Nginx 把 404 统一交给
/404.php:error_page 404 /404.php; - 确保
location = /404.php块存在且能执行 PHP(含fastcgi_pass) - 在
/404.php里用 PHP 做跳转:<?php header('Location: https://www.sogou.com/web?query=' . urlencode($_SERVER['REQUEST_URI'])); exit; ?> - 注意:必须用
urlencode(),否则含空格、中文的路径会出错
实际部署前务必验证三件事
这类跳转看似简单,但线上最容易翻车的是缓存和日志盲区:
- 浏览器和 CDN 会缓存 302 跳转,测试时用
curl -I -H "Cache-Control: no-cache" http://yoursite/xxx绕过 - Nginx 的
access_log默认不记录@named-location内部跳转,加log_not_found off;到对应 location 可减少噪音 - 搜狗/百度对高频跳转有反爬策略,若大量 404 都跳搜索,可能触发验证码或限流——建议只对非 API 路径生效(例如排除
/api/、/static/)
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










