Htaccess recursively replace underscores with hyphens

前端 未结 2 871
醉酒成梦
醉酒成梦 2021-01-07 03:59

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

2条回答
  •  误落风尘
    2021-01-07 04:46

    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.

提交回复
热议问题