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

使用htaccess重写规则时SEO URL出现404错误的解决方法

错误原因分析
  1. 重写规则路径错误:你的.htaccess中重写规则指向根目录下的object.php,但实际该文件存放在/pages/目录下,导致重写后找不到目标文件,请求被转交给index.php处理。
  2. URL末尾斜杠导致查询失效:即使路径修正,访问/object/car/时,捕获的seo_url参数会带有末尾斜杠(即car/),而数据库中存储的seo_url通常是不带斜杠的car,直接查询会匹配不到对应ID。
  3. index.php匹配逻辑限制:index.php仅能匹配/页面文件名形式的URL,无法处理/object/car/这类带二级路径的请求,因此当重写规则失效时直接返回404。另外代码中判断$page !== "…"是错误的,应该是$page !== ".."(上级目录标识),这个小问题会导致目录扫描异常。
修复方案

1. 修正.htaccess重写规则

调整目标路径指向正确的/pages/object.php,同时处理URL末尾的可选斜杠:

RewriteEngine On
RewriteBase /

Options +FollowSymLinks
php_flag display_errors off
php_flag allow_url_fopen off
php_value error_reporting 0

# SSL跳转
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# 处理object的SEO URL,自动移除末尾斜杠并指向正确文件
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^object/(.*?)/?$ /pages/object.php?seo_url=$1 [L,QSA]

# 其他请求转发到index.php
RewriteCond %{REQUEST_FILENAME} !^/index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url_param=$1 [L,QSA]
  • ^(.*?)/?$中的/?匹配末尾可选的斜杠,.*?非贪婪匹配确保捕获的seo_url不带斜杠。
  • 目标路径改为/pages/object.php,对应文件实际位置。

2. 优化object.php参数处理

在object.php中对seo_url做清理,确保即使传入带斜杠的参数也能正常查询:

$seo_url = trim($_GET["seo_url"], '/'); // 移除参数首尾的斜杠

$id = $objects->seo_url_object($seo_url);

3. 修复index.php的目录扫描逻辑

修正循环中的错误判断,避免目录扫描异常:

$url = $_SERVER['REQUEST_URI'];
$url = explode('?', $url)[0];
$pages = scandir($_SERVER['DOCUMENT_ROOT'] . '/pages'); 

$found = false;

foreach ($pages as $page) {  
    if ($page !== "." && $page !== "..") { // 修正为正确的上级目录标识
        $page_name = pathinfo($page, PATHINFO_FILENAME); 
        if ($url === "/" . $page_name) { 
            include $_SERVER['DOCUMENT_ROOT'] . "/pages/" . $page; 
            $found = true; 
            break; 
        } 
    } 
}

if ($url === '/') { 
    include $_SERVER['DOCUMENT_ROOT'] . "/pages/main.php"; 
    $found = true; 
}

if (!$found) { 
    include $_SERVER['DOCUMENT_ROOT'] . "/pages/404.php"; 
} 
验证测试

访问mysite.com/object/car和mysite.com/object/car/,两者都应正确跳转到/pages/object.php,并能通过干净的seo_url=car查询到对应ID,页面正常加载。

内容的提问来源于stack exchange,提问作者Михаил Горячев

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 00:16:09