Issues Replacing underscores to hyphens with .htac

2019-08-03 22:09发布

问题:

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]