.htaccess URL重写求助:index跳转与posts伪静态配置问题
解决方案
1. 处理/index相关路径的外部重定向
添加以下规则到.htaccess文件开头,实现永久301重定向:
RewriteEngine On # 重定向 /index.php、/index.php/ 到 / RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(index\.php)/?\s [NC] RewriteRule ^ / [R=301,L] # 重定向 /index/ 到 / RewriteRule ^index/$ / [R=301,L]
用%{THE_REQUEST}匹配原始请求,避免内部跳转时重复触发重定向,确保仅用户直接访问这些路径时才会执行跳转。
2. Posts路径内部跳转到offers.php
调整规则匹配带结尾斜杠的路径,实现地址栏不变的内部跳转:
# 内部跳转 /posts/{slug}/ 到 offers.php,传递slug参数 RewriteRule ^posts/([^/]+)/$ /offers.php?slug=$1 [L]
之前规则失效原因:
- 你之前的规则
^posts/([^/]*)$仅匹配不带结尾斜杠的路径(如/posts/slug-post-1),但实际访问的是带斜杠的/posts/slug-post-1/,因此无法匹配。 - 强制刷新生效是因为普通刷新时浏览器缓存了旧的错误响应,强制刷新绕过了缓存。
整合所有规则(含.php后缀隐藏功能)
若要保留.php后缀隐藏功能,需调整规则顺序避免冲突:
Options -MultiViews RewriteEngine On # 1. index路径重定向 RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(index\.php)/?\s [NC] RewriteRule ^ / [R=301,L] RewriteRule ^index/$ / [R=301,L] # 2. posts内部跳转 RewriteRule ^posts/([^/]+)/$ /offers.php?slug=$1 [L] # 3. 隐藏.php后缀(仅匹配存在的php文件) RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*)$ $1.php [L]
注意事项:
- 测试前清空浏览器缓存,避免旧重定向缓存干扰结果。
offers.php可通过$_GET['slug']获取文章slug值。
内容的提问来源于stack exchange,提问作者amo01
相关产品推荐
相关产品推荐

