温馨提示×

Ubuntu Apache2如何代理

小樊
43
2026-10-08 03:18:25
栏目: 智能运维

在 Ubuntu 上使用 Apache2 做代理,通常是通过 mod_proxy 相关模块来实现,常见用途有:

  • 反向代理(把请求转发给后端,如 Node、Java、Python)
  • 正向代理(客户端通过 Apache 访问外网,较少用)

下面以 反向代理 为例,讲最常用、最实用的做法。


一、开启代理模块

sudo a2enmod proxy
sudo a2enmod proxy_http
# 如果是 WebSocket
sudo a2enmod proxy_wstunnel

启用后重启 Apache:

sudo systemctl restart apache2

二、配置反向代理(最常用)

示例:把 example.com 代理到本地 3000 端口

编辑站点配置:

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

内容示例:

<VirtualHost *:80>
    ServerName example.com

    ProxyRequests Off
    ProxyPreserveHost On

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

    ErrorLog ${APACHE_LOG_DIR}/example_error.log
    CustomLog ${APACHE_LOG_DIR}/example_access.log combined
</VirtualHost>

启用站点:

sudo a2ensite example.conf
sudo systemctl reload apache2

三、代理指定路径(子路径代理)

ProxyPass /api/ http://127.0.0.1:8080/
ProxyPassReverse /api/ http://127.0.0.1:8080/

访问:

  • http://example.com/api/ → http://127.0.0.1:8080/

四、HTTPS + 代理(推荐)

先用 certbot 生成证书:

sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d example.com

Apache 会自动生成 443 配置,你只需在里面加:

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

五、代理 WebSocket

ProxyPass /ws/ ws://127.0.0.1:3000/
ProxyPassReverse /ws/ ws://127.0.0.1:3000/

六、常见问题

1. 502 Bad Gateway

  • 后端服务没启动
  • 端口写错
  • 防火墙限制

2. 静态资源路径错误

确保后端使用 相对路径 或正确配置 ProxyPassReverse

3. 需要关闭正向代理(安全)

ProxyRequests Off

七、最小可用模板

<VirtualHost *:80>
    ServerName demo.local
    ProxyPass / http://127.0.0.1:5000/
    ProxyPassReverse / http://127.0.0.1:5000/
</VirtualHost>

如果你有 具体场景(比如代理 Docker、Spring Boot、Next.js、WebSocket、内网穿透),我可以给你更精确的配置。

0 踩