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
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.
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]