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

如何在Apache服务器无次级域名部署带react-router-dom的React应用

解决Apache2下React Router刷新404及多应用共存问题

1. 启用必要的Apache模块

先确保Apache开启重写和反向代理所需模块:

sudo a2enmod rewrite proxy proxy_http
sudo systemctl restart apache2

2. 直接在Apache站点配置中配置React路由规则(替代.htaccess)

不依赖.htaccess,直接在站点配置中添加规则更可靠且避免冲突:
编辑你的HTTPS站点配置文件(通常是/etc/apache2/sites-available/000-default-le-ssl.conf或000-default.conf),在<VirtualHost *:443>块内添加以下配置:

# 映射/react_app路径到React应用的build目录
Alias /react_app /var/www/html/react_app_one/build

<Directory /var/www/html/react_app_one/build>
    Options -Indexes +FollowSymLinks
    AllowOverride None
    Require all granted

    # React Router刷新重写规则
    RewriteEngine On
    RewriteBase /react_app/
    # 仅当请求的不是文件、目录、符号链接时,转发到index.html
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^ /react_app/index.html [L]
</Directory>

注意:/var/www/html/react_app_one/build是React执行npm run build后生成的产物目录,请根据实际路径调整。

3. 隔离Node.js反向代理配置

修改/etc/apache2/conf-enabled/下的Node.js代理配置文件,确保代理规则仅针对Node应用的特定路径,避免干扰React和PHP应用:

# 仅转发/node_app开头的请求到Node服务(示例端口3000)
ProxyPass /node_app http://localhost:3000
ProxyPassReverse /node_app http://localhost:3000

这里的/node_app是Node应用对外暴露的路径,localhost:3000是Node服务监听的地址和端口,请根据实际情况修改。

4. 修复文件权限

确保React build目录的权限允许Apache读取:

sudo chown -R www-data:www-data /var/www/html/react_app_one/build
sudo chmod -R 755 /var/www/html/react_app_one/build

5. 验证配置并重启Apache

sudo apache2ctl configtest
sudo systemctl restart apache2

保留已正确配置的React项目设置

你之前在package.json中添加的"homepage": "/react_app"以及<Router basename={'/react_app'}>配置是正确的,无需修改。


内容的提问来源于stack exchange,提问作者ヴァルガスアルド

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:35:25