apache - 301重定向重写规则用连字符替换下划线并删除子目录

标签 apache .htaccess redirect mod-rewrite url-rewriting

我需要帮助为 .httaccess 文件夹中的以下链接结构创建重写规则/301 重定向。

来源网址:www.example.com/sub_directory/product_name_1.html

目标网址:www.example.com/prodcut-name-1.html

此时重定向的要求如下:

  • 删除/sub_directory/
  • 将所有下划线“_”更改为连字符“-”

不幸的是我的正则表达式不是很好。我尝试四处搜索,但其他帖子中类似问题的解决方案对我不起作用(例如 here )

任何有关此问题解决方案的帮助将不胜感激。另外,如果您可以请解释一下原因/方式。我希望能够更好地理解这一点。

最佳答案

Answer from @Walf很接近,但需要一些改变,例如正则表达式 anchor 和 DPI 标志。

您可以在网站根目录 .htaccess 的顶部使用这些规则:

RewriteEngine On

# remove /sub_directory/ when there is no _ left
RewriteRule ^sub_directory/([^_]+)$ /$1 [R=301,NC,NE,L]

# use recursion based rule to replace _ by -
RewriteRule ^(sub_directory/[^_]*)_+(.*)$ $1-$2 [NC,N,DPI]

# rest of your rules go here

关于apache - 301重定向重写规则用连字符替换下划线并删除子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40752336/

相关文章:

php - 有什么方法可以简化 linux 和 windows 的 php 应用程序的安装?

apache - Apache2中的子文件夹目录浏览

apache - 允许在 URL/URI w/o 编码中使用非查询问号 "?"

redirect - 如何重定向到 Angular2 中的外部 URL?

PHP mail() 从命令行工作但不是 apache

java - 如何通过 Java 从 Outlook 发送电子邮件?

.htaccess - 使用正则表达式将一个 URL 重定向到另一个 URL?

apache - 将站点从本地移动到 Ubuntu 服务器

.htaccess 将 root 重定向到特定页面

html - 将目录重定向到目录中的文件