htaccess rewrite rule ends in an infinite loop

人盡茶涼 提交于 2019-12-11 11:27:56

问题


I would like to permanently redirect

www.example.com/event/title-goes-here to www.example.com/event/jazz/title-goes-here

with a regex in my htaccess file.

I currently have:

RewriteEngine on
RewriteRule ^event/(.*)$ http://www.example.com/event/jazz/$1 [R=301,L]

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.

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.

EDIT/UPDATE

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]

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';

回答1:


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]


来源:https://stackoverflow.com/questions/25165910/htaccess-rewrite-rule-ends-in-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!