.htaccess配置故障:/news路径404与无限重定向问题求助
解决.htaccess中/news访问404及循环重定向问题
问题分析
- 访问
/news时出现404:现有规则只处理了/news/{slug}的情况,没有匹配/news本身的路由,服务器找不到对应资源。 - 添加
^([^/]*)/?$规则后循环重定向:这个规则会匹配根目录下所有不带子路径的请求(包括latest.php),导致latest.php被强制转发到news.php,而news.php又重定向回latest.php,形成死循环。
修复步骤
1. 更新.htaccess规则
添加专门匹配/news的规则,确保请求能转发到news.php触发重定向逻辑,同时避免宽泛规则影响其他文件:
Options -MultiViews RewriteEngine On # 阻止后续规则处理已重定向的请求 RewriteCond %{ENV:REDIRECT_STATUS} 200 RewriteRule ^ - [L] # 处理带slug的新闻URL:/news/{slug} → news.php?article_slug={slug} RewriteRule ^news/([\w\d-]+)$ /news.php?article_slug=$1 [QSA,L] # 处理不带slug的/news路径:直接转发到news.php RewriteRule ^news$ /news.php [L,QSA] # 反向重写:将/news.php?article_slug={slug}重定向到友好URL RewriteCond %{QUERY_STRING} article_slug=([\w\d-]+) RewriteRule ^news.php$ /news/%1 [R,L] # 分类路由规则(原规则修正:$2未捕获,若不需要page参数可保留,需要则补充捕获) RewriteRule ^category/([\w-]+)/?$ /category.php?category_slug=$1 [QSA,L]
2. 修正PHP重定向逻辑
原代码中empty($_GET)判断不够精准,且相对路径可能引发问题,改成绝对路径并精准判断article_slug参数:
// 检查article_slug参数是否存在且非空 if (!isset($_GET['article_slug']) || trim($_GET['article_slug']) === '') { // 使用绝对路径跳转,避免相对路径导致的层级问题 header("Location: /latest.php"); exit(); // 用exit替代die,语义更清晰 } $article_slug = $_GET['article_slug'];
验证效果
- 访问
http://localhost/news:自动转发到news.php,触发重定向后跳转到/latest.php,无循环问题。 - 访问
http://localhost/news/example-1:正常映射到news.php?article_slug=example-1,显示对应文章。 - 访问
http://localhost/news.php?article_slug=example-1:自动重定向到友好URL/news/example-1。 - 其他文件(如
latest.php、category.php)可正常访问,不受规则干扰。
内容的提问来源于stack exchange,提问作者Nashie
相关产品推荐
相关产品推荐

