Htaccess recursively replace underscores with hyphens

前端 未结 2 853
醉酒成梦
醉酒成梦 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.

    0 讨论(0)
  • 2021-01-07 04:50

    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]
    
    0 讨论(0)
提交回复
热议问题