mod_rewrite用加号替换下划线并将数据传递给新URL

时间:2015-11-10 18:35:47

标签: .htaccess mod-rewrite

我最近切换到Wordpress,我不想丢失一些旧页面。 旧网站的网页使用以下网址格式

domain.name/gallery/word1_word2_word3_wordX.html

我需要将这些链接转换为:

domain.name/?s=word1+word2+word3+wordX&post_type=product

基本上我需要在gallery /之后获取所有内容,删除.html,用加号替换下划线并将其传递给domain.name/?s=和& post_type = product

之间的新网址格式

感谢任何帮助。 谢谢。

1 个答案:

答案 0 :(得分:1)

我玩了一下,想出了一个有效的解决方案:

RewriteEngine On

# Note: This line is important! Without it, your URLs will look like example.com/home/you/public_html/gallery/etc, which is bad.
RewriteBase /

# Replace any _ with + and redirect
RewriteRule ^gallery\/(.*)_(.*) gallery/$1+$2 [R=301]
# Replace gallery/whatever.html with /?s=whatever&post_type=product
RewriteRule ^gallery/(.*)\.html /?s=$1&post_type=product [R=301]

这转变

http://example.com/gallery/foo_bar_baz_bam.html

进入

http://example.com/?s=foo+bar+baz+bam&post_type=product

我借鉴this postthis one来提出这个问题;你可能会发现那些有用的东西。

注意:这会对重写的每个阶段进行重定向(每_一个,最后一个转换一个)。理论上,在第一个[N][R=301]相当于RewriteRule中使用.htaccess代替while,只能进行一次重定向}循环),但我无法在不创建无限循环的情况下使其工作。