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

如何处理URL目录篡改,让多级无效路径跳转至404错误页?

问题描述

当前.htaccess配置与数据库连接运行正常,但存在以下异常:

  • 访问www.example.com/dsadsada或www.example.com/news/dsadsa时,能正常显示404错误页;
  • 访问www.example.com/news/besthotelinthearea2019/dsadsadsadsa时,不会跳转至404错误页,反而显示“2019年最佳酒店”的新闻内容,但页面样式丢失。

需要修改配置,让此类多层级的错误请求直接重定向到404错误页。

当前.htaccess代码如下:

RewriteEngine on

ErrorDocument 404 /error.php
ErrorDocument 300 /error.php

RewriteRule ^index.html$ / [R=301,L]
RewriteRule ^(.*)/index.html$ /$1/ [R=301,L]

RewriteCond %{THE_REQUEST} ^.*/index\.php 
RewriteRule ^(.*)index.php$ /$1 [R=301,L] 

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

RewriteRule ^news/([0-9a-zA-Z_-]+) news.php?url=$1 [NC,L]

RewriteRule ^sectioncategory/([0-9a-zA-Z_-]+) sectioncategory.php?category=$1 [NC,L] 
解决方案

问题根源在于news和sectioncategory的重写规则没有限制路径结尾,导致多层级路径(如news/xxx/yyy)会被截断匹配,将xxx/yyy作为参数传给对应PHP文件,而PHP文件仅识别xxx部分,从而出现显示内容但样式丢失的情况。

修改方法是在两条重写规则的正则末尾添加$,严格匹配路径结尾:

# 修改后的news重写规则
RewriteRule ^news/([0-9a-zA-Z_-]+)$ news.php?url=$1 [NC,L]

# 修改后的sectioncategory重写规则
RewriteRule ^sectioncategory/([0-9a-zA-Z_-]+)$ sectioncategory.php?category=$1 [NC,L]

原理说明

添加$后,正则表达式会强制匹配到URL路径的末尾,只有当news/或sectioncategory/后面紧跟一个符合规则的字符串(无后续层级)时,才会触发重写转发。如果是news/xxx/yyy这类多层级路径,不会匹配任何重写规则,Apache会尝试查找对应文件或目录,找不到则自动触发404错误页。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:05:23