多Rewrite规则配置引发500错误,寻求友好URL实现方案
解决Apache Rewrite规则导致的500错误及实现友好URL映射
你的配置出现500错误的核心原因是第一条RewriteRule ^(.*) /index.php?category=$1 [L]会匹配所有请求,包括重写后的/index.php请求,导致服务器陷入无限循环重定向,最终触发500错误。
以下是修正后的完整配置,可实现你需要的URL映射:
Options +FollowSymLinks RewriteEngine on # 排除实际存在的文件和目录,避免静态资源(如css/js/img)被重写 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 匹配三级路径:domain.com/分类/子分类/用户ID RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ /index.php?category=$1&subcategory=$2&userid=$3 [L] # 匹配二级路径:domain.com/分类/子分类 RewriteRule ^([^/]+)/([^/]+)$ /index.php?category=$1&subcategory=$2 [L] # 匹配一级路径:domain.com/分类 RewriteRule ^([^/]+)$ /index.php?category=$1 [L]
配置说明:
- RewriteCond规则:先判断请求的路径不是实际存在的文件或目录,确保只有动态请求才会被重写,不影响静态资源的正常访问。
- 规则顺序:从最长的URL(三级路径)开始匹配,再依次处理二级、一级路径,避免短路径规则提前拦截长URL的匹配。
[^/]+匹配模式:仅匹配不含斜杠的字符,相比.*更精准,避免匹配范围过大导致的错误。
配置生效后,可实现以下映射:
domain.com/GetAnnouncements→domain.com/index.php?category=GetAnnouncementsdomain.com/Persona/GetAchievements→domain.com/index.php?category=Persona&subcategory=GetAchievementsdomain.com/Persona/GetAchievements/2→domain.com/index.php?category=Persona&subcategory=GetAchievements&userid=2
内容的提问来源于stack exchange,提问作者szalik.dev
相关产品推荐
相关产品推荐

