htaccess rewrite rule ends in an infinite loop

2019-08-12 04:01发布

问题:

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]