.htaccess重写规则问题:404异常、批量重写及URL美化求助
问题解决方案
1. 非根目录404跳转异常
原因
- 现有规则仅排除了存在的文件,未排除存在的目录;当访问存在目录下的不存在路径时,Rewrite规则的条件会触发,但后续无匹配规则,导致Apache的ErrorDocument未正确生效。
- 部分RewriteRule未添加
[L]标志,可能引发规则链的意外执行。 - 子目录若存在独立
.htaccess,会覆盖根目录的ErrorDocument配置。
修复方案
- 补充排除存在目录的RewriteCond;
- 为所有RewriteRule添加
[L]标志; - 检查子目录
.htaccess,同步ErrorDocument配置(若有)。
2. 批量处理重写规则
优化思路
手动逐个配置规则效率低,可通过动态匹配同名文件实现批量映射,无需重复定义单条规则。
实现方案
通过规则自动匹配请求路径对应的.php或.html文件(优先匹配php),替换原有所有单条重写规则:
# 批量映射到同名PHP文件 RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^([a-z0-9-]+)$ $1.php [L] # 批量映射到同名HTML文件 RewriteCond %{REQUEST_FILENAME}.html -f RewriteRule ^([a-z0-9-]+)$ $1.html [L]
注:正则[a-z0-9-]+匹配仅包含小写字母、数字、连字符的路径,若需支持其他字符可调整正则范围。
3. 动态链接转静态形式
实现规则
添加以下RewriteRule(需放在批量规则之后,避免冲突),将多级静态路径转发到list.php并传递url参数:
# 排除已定义的静态路径,避免冲突 RewriteCond %{REQUEST_URI} !^/(search|our-story|blog|contact|faq|pricing|register|login|dashboard|404)$ # 匹配所有多级路径,转发到list.php RewriteRule ^(.+)$ list.php?url=$1 [L,QSA]
QSA标志用于保留原有请求参数(若有);- 正则
^(.+)$匹配所有非空路径,若需限制为两级路径(如city-location/listing-name),可改为^([^/]+/[^/]+)$。
修改后的完整.htaccess配置
RewriteEngine On RewriteBase / # Exclude rewriting for specific file types, existing files and directories RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !\.(css|js|png|jpg|gif)$ # 批量映射规则 RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^([a-z0-9-]+)$ $1.php [L] RewriteCond %{REQUEST_FILENAME}.html -f RewriteRule ^([a-z0-9-]+)$ $1.html [L] # 动态转静态规则 RewriteCond %{REQUEST_URI} !^/(search|our-story|blog|contact|faq|pricing|register|login|dashboard|404)$ RewriteRule ^(.+)$ list.php?url=$1 [L,QSA] # 404 Page ErrorDocument 404 /404.html
内容的提问来源于stack exchange,提问作者Coderz
相关产品推荐
相关产品推荐

