我想永久重定向
www.example.com/event/title-goes-here to www.example.com/event/jazz/title-goes-here
在我的htaccess文件中使用正则表达式。
我目前有:
RewriteEngine on RewriteRule ^event/(.*)$ http://www.example.com/event/jazz/$1 [R=301,L]但这导致无限循环(它转到example.com/event/jazz/jazz/jazz/jazz等),因为/ event / part是相同的。
如何使用重写规则进行重写,并考虑到人们可以访问example.com/event/title-goes-here和example.com/event/title-goes-here/ (因此使用尾部斜杠)同时仍然正确地进行重定向。
编辑/ UPDATE
根据anubhava的回答,我的完整.htaccess文件现在看起来像这样(忘了提到还有一个重写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的事情,但是当我想到路由文件时,我想这可能会因重写而混乱?
$route['event/jazz/(:any)'] = 'event/view/$1'; $route['(:any)'] = 'pages/view/$1';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';最满意答案
是的,它会循环,因为源和目标URI都匹配您的正则表达式模式。
使用此规则来修复它:
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]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]更多推荐
发布评论