Htaccess recursively replace underscores with hyphens

こ雲淡風輕ζ 提交于 2020-05-08 15:45:06

问题


I'm trying to redirect all URLs with underscores to the same URL but with underscores replaced by hyphens.

I've tried many examples online but these either provide server errors or seem to result in a loop that crashes my server.

From what I've read the following should work:

RewriteRule ^([^_]*)_([^_]*_.*) $1-$2 [N]
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,R=301]

OR

RewriteRule ^(.*)_(.*)$ $1-$2 [N,E=redirect:true]
RewriteCond %{ENV:redirect} ^true$
RewriteRule (.*) $1 [R=301]

However these do not, instead they seem to cause pages to load for a while and then timeout / 404.

Some example URLs that I need to redirect are as follows:

https://domain.com/blog/this_is_a_post_5
https://domain.com/blog/i_am_a_post_12
https://domain.com/forum/i_am_a_forum_post_15

How can I replace the underscores with hyphens in the above in as few rules as possible?


回答1:


One of these implementations will cause 500 internal error if there are more than 10 underscores to be replaced by hyphen since default value of LimitInternalRecursion variable is 10.

Here is one way you can make these replacements work for 20 underscores:

RewriteEngine On

# when there are more than one _ then "recursively" replace it by -
RewriteRule ^([^_]*)_+([^_]*_.+)$ $1-$2 [N,DPI]

# when there is only one / then replace it by _ and redirect
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [NE,L,R=301]

Reason why it works for more than 10 replacements because we are using N instead of L flag in first rule that results in improving the overall performance.




回答2:


You can use that:

RewriteRule ^([^_]*)_([^_]*_.*)$ $1-$2 [L,NE]
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,NE,R=301]

After @anubhava explanation. If big number of underscores can be a problem. You can use that (without variables):

RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*_.*)$ $1-$2-$3-$4 [L,NE]
RewriteRule ^([^_]*)_([^_]*_.*)$ $1-$2 [L,NE]
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,NE,R=301]


来源:https://stackoverflow.com/questions/28132730/htaccess-recursively-replace-underscores-with-hyphens

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