如何通过.htaccess移除URL中的Products/Description路径段
解决.htaccess移除URL中Products/Description路径段的问题
你需要将https://test.com/Products/Description/logitech/Id-12这类URL中的Products/Description路径段移除,变成https://test.com/logitech/Id-12,但当前的Rewrite规则逻辑完全搞反,且位置错误,导致无法生效。
你的现有.htaccess配置:
RewriteEngine On DirectorySlash Off # Remove WWW RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [R=302,L] # Remove Trailing Slashes RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{THE_REQUEST} \s(.+?)//+[?\s] RewriteRule ^ %1 [R=302,L] # Reroute to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] # Remove Products/Description ===> not working RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ Products/Description/$1$2 [L]
问题根源
你写的无效规则是把用户请求的URL重写到Products/Description/$1$2,相当于给URL额外添加这段路径,和需求完全相反;同时规则里的$2没有对应的捕获组,属于无效引用;最关键的是,这条规则放在了路由到index.php的规则后面,而[L]标志会让Apache停止执行后续规则,导致这条规则根本不会被触发。
正确解决方案
需要添加一条外部重定向规则,把包含Products/Description的旧URL跳转到移除后的新URL,且必须将这条规则放在路由到index.php的规则之前。
修改后的完整.htaccess配置:
RewriteEngine On DirectorySlash Off # Remove WWW RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [R=302,L] # Remove Trailing Slashes RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{THE_REQUEST} \s(.+?)//+[?\s] RewriteRule ^ %1 [R=302,L] # 移除Products/Description并跳转到新URL RewriteRule ^Products/Description/(.*)$ /$1 [R=302,L,NC] # Reroute to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L]
规则说明
- 重定向规则:
^Products/Description/(.*)$匹配以Products/Description/开头的URL,$1捕获后续所有内容,然后跳转到/$1(即移除目标路径段后的新URL) [NC]标志忽略URL大小写,[R=302]为临时重定向,测试确认无误后可改为[R=301]永久重定向- 必须将这条规则放在路由到
index.php的规则之前,否则请求会先被转发到index.php,无法触发重定向
内容的提问来源于stack exchange,提问作者Pierre
相关产品推荐
相关产品推荐

