如何配置Apache实现Angular与Spring Boot跨端口请求转发?
Apache反向代理配置方案(适配你的Angular + Spring Boot场景)
没问题,我来帮你搞定Apache的转发配置,同时还会补上Angular单页应用的路由兼容配置(避免刷新页面404的坑)。
第一步:启用Apache必要模块
首先得确保Apache开启了反向代理和重写相关的核心模块,在终端执行以下命令(Debian/Ubuntu环境,CentOS/RHEL只需把apache2换成httpd即可):
sudo a2enmod proxy sudo a2enmod proxy_http sudo a2enmod rewrite
第二步:配置Apache(两种可选方式)
方式一:修改虚拟主机配置(推荐)
找到你的Apache虚拟主机配置文件(通常在/etc/apache2/sites-available/000-default.conf或自定义域名的.conf文件),添加/替换以下内容:
<VirtualHost *:80> ServerName myServerIP # 有域名的话可以换成你的域名 # 处理Angular应用的静态资源与前端路由 DocumentRoot /var/www/asicat <Directory /var/www/asicat> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted # 解决Angular单页应用刷新404问题 RewriteEngine On RewriteBase /asicat/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /asicat/index.html [L] </Directory> # 反向代理Spring Boot API请求 ProxyPass /asicat-rs http://localhost:8092/asicat-rs ProxyPassReverse /asicat-rs http://localhost:8092/asicat-rs ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
方式二:使用.htaccess文件(目录覆盖已开启时可用)
如果你的Apache允许.htaccess生效(已设置AllowOverride All),可以在/var/www/asicat目录下创建.htaccess文件,写入以下内容:
# 处理Angular前端路由 RewriteEngine On RewriteBase /asicat/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /asicat/index.html [L] # 反向代理API请求 RewriteEngine On RewriteRule ^asicat-rs/(.*)$ http://localhost:8092/asicat-rs/$1 [P,L] ProxyPassReverse /asicat-rs/ http://localhost:8092/asicat-rs/
第三步:重启Apache服务
配置完成后,重启Apache让配置生效:
sudo systemctl restart apache2 # Debian/Ubuntu # CentOS/RHEL环境执行:sudo systemctl restart httpd
配置说明
ProxyPass和ProxyPassReverse必须配对使用:前者负责把前端的/asicat-rs请求转发到后端8092端口,后者确保后端返回的重定向、Cookie等信息能正确映射回前端地址。- Angular的重写规则:因为Angular是单页应用,所有前端路由对应的物理文件不存在,需要把非静态资源的请求都转发到
index.html,避免刷新页面时出现404。 - 你Spring Boot里配置的
server.use-forward-headers=true已经正确开启,后端可以获取到真实的客户端IP等信息,无需额外调整。
现在测试一下:访问http://myServerIP/asicat应该能正常打开Angular应用,调用/asicat-rs/*的API时,Apache会自动转发到8092端口的后端服务。
内容的提问来源于stack exchange,提问作者NaN
相关产品推荐
相关产品推荐

