301重定向的正则表达式缩短了Wordpress中的永久链接URL

时间:2016-06-07 20:55:25

标签: regex wordpress .htaccess redirect

我是regex的新手,所以这可能是一个过于简单的问题。

我有一个使用永久链接的Wordpress网站,该网站包含大约1000个帖子,其中包含使用此常规格式的网址:

http://webdomain.com/123456/name-of-a-post/

我想创建一个重定向规则,将传入流量指向此永久链接方案:

http://webdomain.com/name-of-a-post/

基本上,我想缩短网址以删除帖子ID。

这是正则表达式适合的吗?如果是这样,哪个正则表达式会起作用?

1 个答案:

答案 0 :(得分:0)

描述

(https?:\/\/[^\/]+)\/[0-9]{6}(\/\S*)

替换为: $1$2

Regular expression visualization

此正则表达式将执行以下操作:

  • 会找到内容为六位数的网址
  • 允许您删除id substring

实施例

现场演示

https://regex101.com/r/sY0xQ1/1

示例文字

http://webdomain.com/123456/name-of-a-post/

重播后

http://webdomain.com/name-of-a-post/

解释

NODE                     EXPLANATION
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    http                     'http'
----------------------------------------------------------------------
    s?                       's' (optional (matching the most amount
                             possible))
----------------------------------------------------------------------
    :                        ':'
----------------------------------------------------------------------
    \/                       '/'
----------------------------------------------------------------------
    \/                       '/'
----------------------------------------------------------------------
    [^\/]+                   any character except: '\/' (1 or more
                             times (matching the most amount
                             possible))
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------
  \/                       '/'
----------------------------------------------------------------------
  [0-9]{6}                 any character of: '0' to '9' (6 times)
----------------------------------------------------------------------
  (                        group and capture to \2:
----------------------------------------------------------------------
    \/                       '/'
----------------------------------------------------------------------
    \S*                      non-whitespace (all but \n, \r, \t, \f,
                             and " ") (0 or more times (matching the
                             most amount possible))
----------------------------------------------------------------------
  )                        end of \2
----------------------------------------------------------------------