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

WordPress中基于slug前缀的404页面自定义重定向需求

基于Slug的404差异化重定向实现方案

根据需求,核心是在触发404时判断请求路径的前缀,分两种逻辑处理。下面分不同部署环境给出具体实现方案:

Nginx 服务器配置

直接在Nginx的server块中配置404处理逻辑,通过正则匹配判断Slug前缀:

server {
    # 你的域名、根目录等常规配置...

    # 将404请求转发到自定义处理位置
    error_page 404 @handle_404;

    location @handle_404 {
        # 匹配以/news开头的请求路径(不区分大小写)
        if ($uri ~* ^/news) {
            # 301永久重定向到你的自定义新闻类404页面
            return 301 /custom-news-404;
        }
        # 其他所有404请求返回默认404页面
        return 404 /default-404.html;
    }
}

Apache 服务器配置

通过.htaccess文件实现,需确保开启mod_rewrite模块:

# 启用URL重写引擎
RewriteEngine On

# 先判断请求的文件/目录是否不存在(触发404的前提)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 匹配以/news开头的路径,重定向到自定义页面
RewriteRule ^news(.*)$ /custom-news-404 [R=301,L]

# 剩余404请求指向默认404页面
ErrorDocument 404 /default-404.html

后端框架层面实现

如果项目基于后端框架,可以在全局异常/404处理逻辑中添加判断:

Node.js Express 示例

const express = require('express');
const path = require('path');
const app = express();

// 你的业务路由配置...

// 全局404处理中间件(放在所有路由之后)
app.use((req, res) => {
    const requestPath = req.path;
    if (requestPath.startsWith('/news')) {
        // 重定向到自定义新闻类404页面
        res.redirect(301, '/custom-news-404');
    } else {
        // 返回默认404页面
        res.status(404).sendFile(path.join(__dirname, 'public/default-404.html'));
    }
});

app.listen(3000);

PHP Laravel 示例

修改app/Exceptions/Handler.php中的render方法:

<?php

namespace App\Exceptions;

use Illuminate\Http\Request;
use Throwable;

class Handler extends ExceptionHandler
{
    // ... 其他默认代码

    public function render($request, Throwable $e)
    {
        // 判断是否是404异常
        if ($this->isHttpException($e) && $e->getStatusCode() === 404) {
            $requestPath = $request->path();
            // 检查路径是否以news开头
            if (str_starts_with($requestPath, 'news')) {
                // 301重定向到自定义页面
                return redirect()->to('/custom-news-404', 301);
            } else {
                // 返回默认的404视图
                return response()->view('errors.404', [], 404);
            }
        }

        return parent::render($request, $e);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:09:16