大网数据广告活动
网站运营与故障问答

301 Redirects what does ([a-z]+)-(.*) and ([0-9]+)-(.*) mean

· 52CE 我爱测

I just checked an .htaccess file with some custom redirects. There are two redirects I don't fully understand: RedirectMatch 301 ^/news/([0-9]+)-(.*) /blog RedirectMatch 301 ^/news/([a-z]+)-(.*)/$ /blog/$1 Both redirects are redi…

问题原文

原帖链接 · public9nf · CC BY-SA 4.0

I just checked an .htaccess file with some custom redirects. There are two redirects I don't fully understand:

RedirectMatch 301 ^/news/([0-9]+)-(.*) /blog
RedirectMatch 301 ^/news/([a-z]+)-(.*)/$ /blog/$1

Both redirects are redirecting the subfolders or pages inside the news directory but I can't fully grab how because I don't understand the following parts [0-9]+)-(.*) and ([a-z]+)-(.*). What do they exactly mean?

已采纳解答

原帖链接 · Shahzeb Qureshi · CC BY-SA 4.0

The patterns you're confused about are nothing but regular expression functions. The ([0-9]+)-(.*) and ([a-z]+)-(.*) patterns each have two groups in them. Groups in regex are classified as anything within (). The contents of the group are then matched according to the criteria specified.

  1. In the group ([0-9]+) the criteria is to match one or more than one number. This does not include any alphabets or special characters
  2. In the group ([a-z]+) the criteria is to match one or more than one lower case characters. This does not include space, numbers, upper case characters etc.
  3. In the group (.*) the criteria is to match any character irrespective of whether it is an alphabet, number, special character etc.

In your .htaccess the following things are happening:

  1. RedirectMatch 301 ^/news/([0-9]+)-(.*) /blog
  2. RedirectMatch 301 ^/news/([a-z]+)-(.*)/$ /blog/$1

In statement 1 the pattern ^/news/([0-9]+)-(.*) is matched when the URL is example.com/news/23-article and is simply redirected to example.com/blog

In statement 2, the pattern ^/news/([a-z]+)-(.*)/$ is matched when the URL is example.com/news/latest-article/ and is redirected to example.com/blog/latest.

Notice the $1 in the destination URL in statement 2. The $1 is used to fetch the contents of group 1 that has matched, hence we get the destination URL as /blog/latest because the content of the first group is the word latest

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2019-05-15)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。