htaccess重写规则以无限循环结束 [英] htaccess rewrite rule ends in an infinite loop
问题描述
我想永久重定向
www.example.com/event/title-goes-here
至www.example.com/event/jazz/title-goes-here
我的htaccess文件中带有正则表达式.
with a regex in my htaccess file.
我目前有:
RewriteEngine on
RewriteRule ^event/(.*)$ http://www.example.com/event/jazz/$1 [R=301,L]
但是由于/event/部分相同,这会导致无限循环(进入example.com/event/jazz/jazz/jazz/jazz
等).
But this results in an infinite loop (it goes to example.com/event/jazz/jazz/jazz/jazz
etc) because the /event/ part is the same.
如何使用重写规则进行此重写,并且还要考虑到人们可以在仍然正确进行重定向的情况下转到example.com/event/title-goes-here
和example.com/event/title-goes-here/
(带有斜杠).
How can I use the rewrite rule to make this rewrite, and also in a way that it takes into account that people can go to example.com/event/title-goes-here
AND example.com/event/title-goes-here/
(so with a trailing slash) while still correctly making the redirect.
编辑/更新
基于anubhava的答案,我现在完整的.htaccess文件如下所示(忘了提到index.php也有重写):
Based on anubhava's answer my complete .htaccess file now looks like this (forgot to mention there's also a rewrite on index.php):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
RewriteRule ^event/([^/]+)/?$ /event/jazz/$1 [R=301,L,NC,NE]
也忘了提一下我正在使用CodeIgniter,并且在routing.php中有以下列出的路由选项(不知道这是否重要).以为这纯粹是.htaccess的问题,但是当我想到路由文件时,我发现这可能与重写混为一谈?
Also forgot to mention I'm using CodeIgniter and in my routing.php there are routing options listed below (don't know if this matters). Thought this was purely a .htaccess thing but when I thought about the routing file I figured that maybe this messes with the rewriting?
$route['event/jazz/(:any)'] = 'event/view/$1';
$route['(:any)'] = 'pages/view/$1';
推荐答案
是的,它会循环,因为源和目标URI都与您的正则表达式模式匹配.
Yes it will loop because source and target URIs both match your regex pattern.
使用此规则对其进行修正:
Use this rule to fix it:
RewriteEngine on
RewriteRule ^event/([^/]+)/?$ /event/jazz/$1 [R=301,L,NC,NE]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php/$0 [PT,L]
这篇关于htaccess重写规则以无限循环结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!