使用htaccess搜索并替换响应内容中的关键字


Search and replace a keyword in the response content using htaccess

我需要在100,000个文件中重写关键字(旧域名),我无法在数据库中搜索和替换它。也许有一个解决方案与htaccess?

老:黄狗总是点击www.domainname1.tld

新:黄狗总是点击www.domainname2.tld

PHP:

$bodytag = "the yellow dog clicks always www.domainname1.tld";
$bodytag = str_replace("domainname1.tld", "domainname2.tld", $bodytag);

我不知道如何在htaccess中做到这一点。有一些Apache模块被设计用来操作内容。例如:mod_substitute.

http://httpd.apache.org/docs/2.2/mod/mod_substitute.html

<Location />
    AddOutputFilterByType SUBSTITUTE text/html
    Substitute s/www.domainname1.tld/www.domainname2.tld/ni
</Location>

信用:http://corpocrat.com/2008/09/19/install-apache-mod_substitute/

修改文件内容超出了.htaccess文件或Apache的范围。

如果一个链接指向一个域,该域将被调用。您可以在该域上添加重定向(这里有一个如何重定向的示例),但您无法阻止请求最终到达旧域。

我有一个类似的例子,我们移动了很多文件到一个新的文件夹结构:

旧结构:

/css/
/images/
/js
/*.html
新结构:

/common/css/
/common/images/
/common/js
/<various_html_folders/*.html

问题是我的html文件通过相对路径引用css, js和图像,并且使用新的结构,我将不得不更新数千个这些引用。

所以我在Apache中遇到了mod_rewrite,它在发送到客户端之前重写了响应体。我在我的。htaccess文件中添加了以下4行,以便将所有href="css/更改为href="/common/css/":

AddOutputFilterByType SUBSTITUTE text/html
Substitute 's|href="css/|="/common/css/|i'
Substitute 's|href="js/|="/common/js/|i'
Substitute 's|href="images/|="/common/images/|i'

瞧!Css, javascript和图像可以像以前一样工作,而无需更新任何HTML文件。

免责声明:我还没有研究这样做对性能的影响。请记住,对于您添加的每一行Substitute,都会在整个响应体上执行正则表达式。