使用 Apache 实现反向代理配置及引用资源替换


反向代理(Reverse Proxy)方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器。反向代理目的也各有不同,有用作CDN的,有作为负载均衡的等等。

谈到反向代理软件,不得不提到 nginx,性能高,功能强大,配置简单,作为负载均衡的工具绝对优秀。

然而由于种种原因,本文是基于 Apache 下配置反向代理。

1. 启动相关模块

首先确保Apache有这些模块,在Apache根目录下确认有这些模块,主要包含以下模块:

mod_proxy.so
mod_proxy_http.so
# 以下模块实际并未使用到
# mod_proxy_ajp.so
# mod_proxy_balancer.so
# mod_proxy_connect.so

打开配置conf/httpd.conf文件,将这些模块的注释去掉保存。

2. 修改网站配置文件,打开文件 conf/httpd.conf ,在文件末尾加上如下配置

<VirtualHost *:80>
    ServerName my.suroy.cn
    ServerAlias 
    ProxyRequests Off
    DocumentRoot "X:/My/"

    <Directory "X:/My/">
        Options Indexes FollowSymLinks ExecCGI
        AllowOverride All
        Require all granted
    </Directory>
        
        # 反代设置
    ProxyPass / http://target.suroy.cn/
    ProxyPassReverse / http://target.suroy.cn/
    <proxy http://my.suroy.cn:80>
        AllowOverride All
        Order Deny,Allow
        Allow from all
    </proxy>
    
    # 设置替换网页内容(引用素材等)
    AddOutputFilterByType SUBSTITUTE; text/html text/plain text/xml application/xml
    Substitute "s|target.suroy.cn/|/my.suroy.cn/|ni" 

    CustomLog "logs/my.suroy.cn.access.log" combined
    ErrorLog "logs/my.suroy.cn.error.log"
</VirtualHost>

3. 解决报错

Apache 2.4-mod_substitute.so启用后无法启动Apache-Invalid command ‘AddOutputFilterByType’
启动的时候,得到了报错

AH00526: Syntax error on line 2 of /Apache/conf/extra/httpd-substitute.conf:
Invalid command 'AddOutputFilterByType', perhaps misspelled or defined by a module not included in the server configuration

通过谷歌,找到了官网说明,原来是Apache 2.4之后,要想生效,必须启用另一个模块才可以,即要启用

mod_filter.so
mod_substitute.so

两个模块。启用后,即可正常启动Apache。
注意:该模块可以进行网页引用资源的替换,实现完美反向代理。

参考资料:https://www.docs4dev.com/docs/zh/apache/2.4/reference/mod-mod_substitute.html

声明:Grows towards sunlight |版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - 使用 Apache 实现反向代理配置及引用资源替换


Grows towards sunlight and Carpe Diem