Apache2 – 将一堆指定的path名​​URL重写为一个URL

我需要重写一大堆SEO(大约100左右),以后可能还会增加更多(可能在50-100之后)。 我需要一个灵活的方法来做到这一点,目前我唯一能想到的方法是使用重写引擎编辑.htaccess文件。

例如,我有一大堆这样的URL(请注意,查询string是不相关的,dynamic的,可以是任何东西,我只是纯粹用它作为例子,我只关注path名 – 部分在主机名和查询string之间,如下所示):

http://example.com/ seo_term1 ?utm_source = google&utm_medium = cpc&utm_campaign = seo_term http://example.com/ another_seo_term2 ?utm_source = Facebook&utm_medium = cpc&utm_campaign = seo_term

http://example.com/ yet_another_seo_term3 ?utm_source = example_ad_network&utm_medium = cpc&utm_campaign = seo_term http://example.com/ foob​​ar_seo_term4

http://example.com/ blah_seo_term5 ?test = 1

等等…

他们都被重写(现在): http://example.com/ : http://example.com/

这样做的最有效率的方法是什么,以便我可以在将来添加更多条款?

我遇到的一个解决scheme是做到这一点(在.htaccess文件中):

 RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ / [NC,QSA] 

然而,这个解决scheme的问题是即使是无效的URL(例如http://example.com/blah )也会被重写为http://example.com而不是提供404代码(这是应该的不pipe怎样)。 我仍然试图弄清楚所有这些是如何工作的,而我能想到的唯一方法是在RewriteRule指令之前编写100多个RewriteCond语句(例如: RewriteCond %{REQUEST_URI} =/seo_term1 [NC,OR] ) 。 例如:

 RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} =/seo_term1 [NC,OR] RewriteCond %{REQUEST_URI} =/another_seo_term2 [NC,OR] RewriteCond %{REQUEST_URI} =/yet_another_seo_term3 [NC,OR] RewriteCond %{REQUEST_URI} =/foobar_seo_term4 [NC,OR] RewriteCond %{REQUEST_URI} =/blah_seo_term5 [NC] RewriteRule ^(.*)$ / [NC,QSA] 

但是这对我来说听起来不是很有效率。 有没有更好的办法?

你可以做的第一个改进就是你根本不需要RewriteCond行。

 RewriteRule /seo_term1 / [NC,QSA] 

你现在正在做什么?

你可以做的第二个改进是使用RewriteMap 。 重写映射本身可以在不重新启动Apache的情况下更新。

 RewriteMap seo txt:/etc/apache2/maps/seo.txt RewriteRule (.*) ${seo:$1} [NC,QSA] 

seo.txt包含

 /seo_term1 / /seo_term2 / 

注意:我好几年没有使用RewriteMap了。 上面的configuration可能需要一些调整,由于我的内存不完善。

一个正则expression式应该是相当能够把这个closures。

 RewriteEngine on RewriteCond %{REQUEST_URI} ^\/[^\?]+\?(?=.*(utm_source\=(google|msn|yahoo)))(?=.*(utm_medium\=(cpc|ppc)))(?=.*(utm_campaign\=[a-zA-Z0-9._-]+)) RewriteRule ^(.*)$ / [L,R=301] 

以上只会匹配一个包含所有指定参数的string,而不pipe前导(pre?)string。

编辑…

好的,现在你已经改变了你的问题了。 但是,谢天谢地,它更直接。

 RewriteEngine on RewriteCond %{REQUEST_URI} ^\/(seo_term1|seo_term2)(.*)? RewriteRule ^(.*)$ / [L,R=301] 

只需要改变/编辑/添加值。