【问题标题】:How to redirect URLs with the same substring to a new page如何将具有相同子字符串的 URL 重定向到新页面
【发布时间】:2015-06-04 07:10:38
【问题描述】:

如何将具有相同子字符串的 URL 重定向到新页面

我必须重定向大约 200 个这种类型的 URL:

Redirect 301 /folder/page1.html       http://domain.com/new-a
Redirect 301 /folder/xyz_page1.html   http://domain.com/new-a
Redirect 301 /folder/page2.html       http://domain.com/new-b
Redirect 301 /folder/xyz_page2.html   http://domain.com/new-b

除了字符串“xyz_”之外,“page1.html”/“xyz_page1.html”“page2.html”/“xyz_page2.html”相似

如果我可以为字符串“xyz_”使用某种通配符来编写重定向,例如

Redirect 301 /folder/*page1.html   http://domain.com/new-a
Redirect 301 /folder/*page2.html   http://domain.com/new-b

我只需要重定向其中的一半,而不是 200 个 URL。

有什么建议吗?谢谢。

【问题讨论】:

    标签: apache .htaccess redirect drupal url-redirection


    【解决方案1】:

    使用RewriteRule。确保您启用了 mod-rewrite 并将其放入您站点根目录的 .htaccess 文件中

    RewriteEngine On
    RerwriteRule folder/.*page1\.html$ http://domain.com/new-a [R,L]
    RerwriteRule folder/.*page2\.html$ http://domain.com/new-b [R,L]
    

    【讨论】:

      【解决方案2】:
      RewriteEngine On
      RewriteRule /folder/(.*)page1.html$   http://domain.com/new-a [R=301,L]
      RewriteRule /folder/(.*)page2.html$   http://domain.com/new-b [R=301,L]
      

      曾经工作过 :) 告诉我

      【讨论】:

      • 我可以使用 RedirectMatch 代替 RewriteRule 吗?我想将重定向命令放在 Drupal 根 .htaccess 文件的顶部,而不是放在“RewriteEngine On”部分......只是为了有两个单独的部分:原始的 drupal 代码和我的重定向。
      • “RedirectMatch”是 mod_alias 的一部分,“RewriteRule”是“mod_rewrite”的一部分。两个模块将在处理管道的不同点应用于相同的 URL。因此,最好坚持使用 RewriteRule,因为 RedirectMatch 可能会干扰其他页面 --- 您可以在 .htaccess 文件的两个不同位置使用 RewriteEngine On,例如两个部分,如果这有意义的话,重写引擎。
      • 我不知道我可以在不同的地方使用 RewriteEngine On!我必须用“RewriteEngine Off”关闭前面的部分吗?无论如何我不明白为什么 RewriteRule 更喜欢?
      • 你可以在文件的开头说rewriteEngie On,不,你不需要说它关闭
      【解决方案3】:

      您可以将 RedirectMatch 指令与正则表达式一起使用:

       RedirectMatch 301 ^/folder/page1\.html$       http://domain.com/new-a
      
      RedirectMatch 301 ^/folder/([^_]+)_page1\.html$ http://domain.com/new-b 
      
      RedirectMatch 301 ^/folder/page2\.html$       http://domain.com/new-a
      
      RedirectMatch 301 ^/folder/([^_]+)_page2\.html$       http://domain.com/new-b
      

      【讨论】:

      • 您可以大大简化此正则表达式,如其他答案所示
      • 我不明白你为什么使用 4 Redirects?
      猜你喜欢
      • 1970-01-01
      • 2013-01-09
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 2017-11-19
      • 2022-08-08
      相关资源
      最近更新 更多