Issues Replacing underscores to hyphens with .htaccess

China☆狼群 提交于 2019-12-13 17:47:48

问题


Although I already saw few posts about this thema, I am still having some problems to achieve what I want. My old URL's were like:

http://myhostname.com/offer/1234_Nice_Offer_Cool_Whatever_HEllyeah.htm

And obviously I want to rewrite them to:

http://myhostname.com/offer/1234-nice-offer-cool-whatever-hellyeah.htm

This is the code I tried in .htaccess. This works fine to replace the underscores in URL's which they don't have ANY directory:

RewriteCond %{REQUEST_URI} \.htm$ [NC]    
RewriteRule ^([^_]*)_+(.*)$ $1-$2 [E=underscores:Yes,N] 
RewriteCond %{ENV:underscores} ^Yes$
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]

So, this paire of rules work fine with URL's like:

http://myhostname.com/1234_Some_Section_hellyeah.htm

But when I try the same code for URL's like:

http://myhostname.com/dir1/dir2/dir3/1234_Some_Offer_Or_Section.htm

Then, the server makes an infinite loop (I figure of the [N] flag...) Basically, I would like to know in which way affects a per-directory URL to these rules and why am I getting this infinite loop. Thanks!


回答1:


You don't need N flag. To replace underscore by hyphen recursively following code will work:

RewriteRule ^([^_]+)_(.+?\.htm)$ $1-$2 [L,NC,E=underscores:Yes]

RewriteCond %{ENV:REDIRECT_underscores} ^Yes$
RewriteRule ^([^_]+)$ /$1 [R=301,L]


来源:https://stackoverflow.com/questions/17741708/issues-replacing-underscores-to-hyphens-with-htaccess

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