温馨提示×

apache2如何配置反向代理

小樊
46
2026-10-03 12:27:44
栏目: 编程语言

下面以 Ubuntu/Debian 上的 Apache2 为例,说明如何配置反向代理(Reverse Proxy)。


一、启用必要模块

Apache 反向代理需要以下模块:

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_balancer   # 如需负载均衡
sudo a2enmod lbmethod_byrequests

启用后重启 Apache:

sudo systemctl restart apache2

二、最简单的反向代理示例

假设:

  • 外部访问:http://example.com
  • 后端服务:http://127.0.0.1:8080

编辑虚拟主机配置

sudo nano /etc/apache2/sites-available/example.conf

内容示例:

<VirtualHost *:80>
    ServerName example.com

    ProxyRequests Off
    ProxyPass / http://127.0.0.1:8080/
    ProxyPassReverse / http://127.0.0.1:8080/

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

启用站点:

sudo a2ensite example.conf
sudo systemctl reload apache2

三、只代理部分路径

ProxyPass /api/ http://127.0.0.1:3000/
ProxyPassReverse /api/ http://127.0.0.1:3000/

访问:

  • http://example.com/api/ → 后端 3000 端口

四、HTTPS 反向代理(常见)

1. 启用 SSL 模块

sudo a2enmod ssl

2. 配置 HTTPS 虚拟主机

<VirtualHost *:443>
    ServerName example.com

    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/example.crt
    SSLCertificateKeyFile /etc/ssl/private/example.key

    ProxyRequests Off
    ProxyPass / http://127.0.0.1:8080/
    ProxyPassReverse / http://127.0.0.1:8080/

    # WebSocket 支持(如需要)
    ProxyPass /ws/ ws://127.0.0.1:8080/
    ProxyPassReverse /ws/ ws://127.0.0.1:8080/
</VirtualHost>

五、常见加固配置(推荐)

ProxyPreserveHost On
RequestHeader set X-Forwarded-Proto "https"

防止后端获取错误 IP:

LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b" proxy

六、调试方法

查看错误日志:

sudo tail -f /var/log/apache2/error.log

常见错误:

  • Proxy request forbidden → 没关 ProxyRequests
  • Connection refused → 后端服务未启动
  • DNS resolution failed → 地址写错

如果你有具体场景(如 Node / Spring Boot / Docker / WebSocket / 负载均衡),可以告诉我,我可以给你更精确的配置。

0 踩