带空格双参数URL重写触发403 Forbidden错误的解决求助
问题描述
我有一个PHP文件:
example.com/products/index.php
我的目标是实现访问:
example.com/products/186/Hello to you
并在PHP中通过$_GET['id']获取值186,通过$_GET['cat']获取值“Hello to you”。
但我尝试以下规则后出现403错误:
You don't have permission to access this resource.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument
我的.htaccess规则:
Options -MultiViews RewriteEngine On # HTTP to HTTPS canonical redirect RewriteCond %{HTTP_HOST} example\.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule (.*) https://example.com/$1 [R=301,L] # Abort early if the request already maps to (or looks like) a file or directory RewriteCond %{REQUEST_URI} \.\w{2,4}$ [OR] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^(products)/([^/]*)/?(.*) $1/index.php?id=$2&cat=$3 [L] # 3. Extensionless URLs for other requests (this below works fine and is for something else) RewriteCond %{DOCUMENT_ROOT}/$1.php -f RewriteRule (.*) $1.php [L]
解决方案及修正后的规则
403错误大概率是规则逻辑冲突或重写路径解析问题导致的,以下是修正后的完整规则:
Options -MultiViews RewriteEngine On RewriteBase / # HTTP to HTTPS canonical redirect RewriteCond %{HTTP_HOST} example\.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://example.com/$1 [R=301,L] # 提前终止:请求对应已存在的文件或目录时直接返回 RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] # 处理products的友好URL # 精确匹配数字ID和任意内容的分类名(包含空格,URL中需转义为%20) RewriteRule ^products/(\d+)/(.+)$ products/index.php?id=$1&cat=$2 [L,QSA] # 无扩展名URL处理(保留原逻辑) RewriteCond %{DOCUMENT_ROOT}/$1.php -f RewriteRule ^(.*)$ $1.php [L]
关键修正点说明
- 添加
RewriteBase /:确保相对路径的重写目标能被Apache正确解析,避免路径混乱导致的权限或文件找不到问题。 - 简化提前终止规则:移除
%{REQUEST_URI} \.\w{2,4}$条件,因为%{REQUEST_FILENAME} -f已经会匹配所有存在的文件(包括带扩展名的),多余条件可能导致意外的规则终止。 - 优化products重写正则:
- 用
\d+匹配ID(仅数字),避免无效请求触发规则; - 用
.+匹配分类名(确保至少有内容),支持包含空格的场景(URL中实际为%20,Apache会自动解析为空格存入$_GET['cat']); - 添加
QSA标志:如果URL带有其他查询参数,会自动追加到重写后的请求中,避免参数丢失。
- 用
- 修正正则锚定逻辑:原规则中
/?可能导致分类名前出现空值,优化后直接用/分隔ID和分类名,逻辑更清晰。
内容的提问来源于stack exchange,提问作者Matilda
相关产品推荐
相关产品推荐

