How do I Mod-Rewrite underscores to dashes with 1 to 4 variables and new text?
To change from this:
https://example.com/Text_var1_var2_var3_var4.html
To this:
https://example.com/NewText-var1-var2-var3-var4.html
I've tried this but it gives a 404 error:
RewriteRule ^text_([a-zA-Z] )_?([a-zA-Z]*)_?([a-zA-Z]*)_?\(*([a-zA-Z]*)\)*.html?$ newtext-$1-$2-$3-$4^.html
CodePudding user response:
I'm assuming this should be an external redirect (in order to "correct" the URL), not an internal rewrite, as you appear to be trying to do?
Try it like this instead:
RewriteEngine On
# Handle from 1 to 4 "variables" and "newtext"
RewriteRule ^text_([a-zA-Z0-9] )\.html$ /newtext-$1.html [R=302,L]
RewriteRule ^text_([a-zA-Z0-9] )_([a-zA-Z0-9] )\.html$ /newtext-$1-$2.html [R=302,L]
RewriteRule ^text_([a-zA-Z0-9] )_([a-zA-Z0-9] )_([a-zA-Z0-9] )\.html$ /newtext-$1-$2-$3.html [R=302,L]
RewriteRule ^text_([a-zA-Z0-9] )_([a-zA-Z0-9] )_([a-zA-Z0-9] )_([a-zA-Z0-9] )\.html$ /newtext-$1-$2-$3-$4.html [R=302,L]
Each "variable" is limited to the characters a-z
, A-Z
and 0-9
(although you omitted digits in your example directive, your example URL does strictly contain digits and you've not stated otherwise).
You can do it more "dynamically" to avoid repeating text
and newtext
in each rule, but that would make it arguably more complex and there doesn't seem to be a need considering it would appear to be a static text replacement and a limited number of "variables".
RewriteRule ^text_([a-zA-Z] )_?([a-zA-Z]*)_?([a-zA-Z]*)_?\(*([a-zA-Z]*)\)*.html?$ newtext-$1-$2-$3-$4^.html
This has a number of issues/anomalies:
- You have an erroneous
^
in the substitution string. - You are trying to handle all 1 to 4 variables in a single directive. The problem here is that the number of hyphens in the substitution string is "fixed". So, if there was just one variable (eg.
/text_var.html
) then the resulting substitution would benewtext-var---.html
(if not for the erroneous^
) - which I'm sure is not the intention. - You are allowing any number of optional parentheses surrounding the 4th "variable", but you make no mention of this in your requirements? eg.
/text_one_two_three_(((four).html
would be matched, but onlyone
,two
,three
andfour
are captured. - This is an internal rewrite, not an external redirect. So unless
/newtext-var1-var2-var3-var4.html
maps to a physical file then this requires further rewriting to be resolved correctly (which is unlikely to work).