RedirectMatch 301 ^/news/([0-9]+)-(.*) /blog
RedirectMatch 301 ^/news/([a-z]+)-(.*)/$ /blog/$1
RedirectMatch directive tries to match the regex (2nd argument) with the requested URL-path. If it matches then a redirect response is returned, to redirect the browser to the target URL (3rd argument).
$1 backreference in the target URL of the second example copies text that has matched in the source URL-path. eg. Given a request for
abc part is "copied" in order to redirect to
/blog/abc (see later).
This basically matches 1 or more digits followed by a hyphen (followed by anything). Specifically:
[0-9] - This "character class" (denoted by
]) matches a single character in the range 0-9, ie. a digit.
+ is a "quantifier" and matches 1 or more of the preceding character/group. So it matches 1 or more digits.
- this hyphen is matched literally (it carries no special meaning when used outside of a character class).
.* matches any number of characters (except newline). Specifically
. matches any character (except newline) and
* is a quantifier that matches 0 or more of the preceding character/group. (Contrast with
+ which matches 1 or more.)
- The parentheses
) that surround parts of the regex make "capturing groups", which can be used later using backreferences. However, these are not being used here.
The above can be simplified (since none of the backreferences are used). We just need to match 1 or more digits, followed by a hyphen:
\d is a shorthand character class that matches digits. ie. the same as
Very similar to the above, except it matches 1 or more lowercase letters (a-z), followed by a hyphen, followed by anything, before ending with a literal slash.
$ is an anchor signifying the end of the the string, ie. the end of the URL-path when used here. Conversely,
^ matches the start of the string, ie. the start of the URL-path (as opposed to some point in between).
Contrary to the first regex, the first backreference (
$1) is used in this example, which captures whatever matches
([a-z]+). So, for example,
/news/abc-123/ is redirected to
This can't be simplified as much as the first regex, because of the capturing backreference and trailing slash. But the second group of parentheses could be removed: