在 htaccess 中使用正则表达式进行 301 重定向

编程入门 行业动态 更新时间:2024-10-13 06:16:50
本文介绍了在 htaccess 中使用正则表达式进行 301 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 Wordpress 博客,我将博客文章从我的旧博客重定向到我的新博客,格式如下:

I have a Wordpress blog where I am redirecting blog posts from my old blog to my new blog in the format below:

旧博客称为新闻",新博客简称为博客" - 两者都存在于相同域中的子目录中,如下所示.

The old blog is called 'News' and the new blog is simply called 'Blog' - both exist on the same domain in a subdirectory as indicated below.

旧的新闻"博客结构

www.example/news/new-android-os-3431

新的博客"博客结构

www.example/blog/new-android-os

基本上这个重定向需要做两件事:-

Essentially this redirect needs to do 2 things:-

  • 重定向到博客"目录
  • 在相同的结构中保留帖子名称,但删除 URL 末尾的最后一组数字
  • 我有大约 900 多个帖子需要设置重定向 - 我知道我可以手动添加每个帖子,但这需要一些时间.谁能指出这是否可以直接在 htaccess 文件中使用正则表达式来最小化此过程?

    I have around 900+ posts that I need to setup redirects for - I know I could manually add each one in but that would take some time. Could anyone indicate if this could be using an regular expression directly within the htaccess file to minimise this process?

    我的 htaccess 目前看起来像这样:

    My htaccess currently looks like this:

    # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /news/ RewriteRule ^index.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /news/index.php [L] </IfModule> # END WordPress

    推荐答案

    使用 mod_alias:

    Using mod_alias:

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

    或使用 mod_rewrite:

    or using mod_rewrite:

    RewriteEngine On RewriteRule ^news/(.+?)(-[0-9]+)?$ /blog/$1 [L,R=301]

    更多推荐

    在 htaccess 中使用正则表达式进行 301 重定向

    本文发布于:2023-10-31 13:40:12,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1546248.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:重定向   正则表达式   htaccess

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!