You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu22下Apache2如何配置多域名转发至不同端口服务

Ubuntu 22 下Apache2按域名分发请求到不同后端服务配置步骤

前置检查

操作前先确认两个前提:

  • 域名解析已配置完成:*.domain.example泛解析、gitea.domain.example单独A记录均指向当前服务器公网IP
  • 本地服务状态正常:执行curl 127.0.0.1:4848可返回Rust服务响应,curl 127.0.0.1:3000可返回Gitea响应

首先安装Apache并启用反向代理所需模块:

sudo apt update && sudo apt install apache2 -y
sudo a2enmod proxy proxy_http proxy_wstunnel rewrite headers
sudo systemctl restart apache2

配置Gitea专属虚拟主机

由于泛域名规则会匹配所有二级域名,需要把Gitea的配置放在更高优先级位置(配置文件命名序号更小,Apache会优先加载序号小的站点配置),创建配置文件/etc/apache2/sites-available/000-gitea.conf,写入以下内容:

<VirtualHost *:80>
    ServerName gitea.domain.example
    ProxyPreserveHost On
    ProxyRequests Off

    # 转发常规HTTP请求到本地3000端口
    ProxyPass / http://127.0.0.1:3000/
    ProxyPassReverse / http://127.0.0.1:3000/

    # 适配Gitea WebSocket连接(支持Git操作、在线终端等功能)
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule /(.*) ws://127.0.0.1:3000/$1 [P,L]

    # 向后端传递真实客户端IP
    RequestHeader set X-Real-IP %{REMOTE_ADDR}s
    RequestHeader set X-Forwarded-For %{HTTP:X-Forwarded-For}s
    RequestHeader set X-Forwarded-Proto $scheme
</VirtualHost>

配置泛域名转发规则(指向Rust服务)

创建配置文件/etc/apache2/sites-available/001-rust-service.conf,写入以下内容,配置中显式排除Gitea域名做双重保险:

<VirtualHost *:80>
    ServerName domain.example
    ServerAlias *.domain.example
    ServerAlias !gitea.domain.example

    ProxyPreserveHost On
    ProxyRequests Off

    # 转发所有请求到本地4848端口的Rust服务
    ProxyPass / http://127.0.0.1:4848/
    ProxyPassReverse / http://127.0.0.1:4848/

    # 向后端传递真实客户端IP
    RequestHeader set X-Real-IP %{REMOTE_ADDR}s
    RequestHeader set X-Forwarded-For %{HTTP:X-Forwarded-For}s
    RequestHeader set X-Forwarded-Proto $scheme
</VirtualHost>

启用配置并验证

  1. 禁用Apache默认测试站点,启用新配置的两个站点:
sudo a2dissite 000-default.conf
sudo a2ensite 000-gitea.conf 001-rust-service.conf
  1. 检查配置语法正确性:
sudo apache2ctl configtest

仅当输出Syntax OK时再执行后续操作,若有报错根据提示修正配置文件内容即可

  1. 重载Apache服务让配置生效:
sudo systemctl reload apache2
  1. 访问验证:
    • 访问http://gitea.domain.example可正常打开Gitea页面
    • 访问任意其他二级域名(如http://app.domain.example、http://api.domain.example)均可正常打开Rust服务页面

可选配置:HTTPS证书部署

生产环境建议配置HTTPS,直接用certbot工具自动申请Let's Encrypt证书即可,无需手动编写443端口配置:

sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache

执行后按交互提示选择需要签发证书的域名(包含gitea.domain.example和*.domain.example),工具会自动配置HTTPS规则、HTTP强制跳转HTTPS。

注意:如果Gitea配置文件(默认路径/etc/gitea/app.ini)中ROOT_URL参数之前写的是IP+端口形式,需要修改为https://gitea.domain.example/,修改后执行sudo systemctl restart gitea重启服务,避免页面内链接跳转异常。

内容的提问来源于stack exchange,提问作者Maria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 04:42:22