【问题标题】:Apache configuration for ReactJS with React Router V4带有 React Router V4 的 ReactJS 的 Apache 配置
【发布时间】:2018-11-30 00:18:26
【问题描述】:

我确实有一个使用 ReactJS 和 React Router V4 构建的应用程序,我正在尝试将其发布到生产环境中。

在生产中,我有以下配置的 Apache:

$ cat /etc/apache2/sites-available/000-default.conf

<VirtualHost *:80>
    ServerName myapp.localhost
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    SetEnv APP_HOME /usr/local/bin/myapp
    <Directory "/var/www/html">
        AllowOverride All
    # Don't rewrite files or subdirectories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]
        # Rewrite everything else to index.html to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

在浏览时,我会这样做:

http://192.168.0.100

它会加载我的着陆页。但从那里我无法访问任何其他网址:

http://192.168.0.100/login
http://192.168.0.100/status
http://192.168.0.100/detail/1
http://192.168.0.100/dashboard

我从 Apache 收到以下错误的所有页面:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /status was not found on this server.</p>
<hr>
<address>Apache/2.4.10 (Debian) Server at 192.168.0.100 Port 80</address>
</body></html>

我很确定我的配置有问题(可能是我的 RewriteCond/RewriteRule),但不知道如何解决它。

【问题讨论】:

    标签: reactjs apache debian apache2 react-router-v4


    【解决方案1】:

    我知道这已经晚了一年,但我想分享这个解决方案,假设使用的是 Ubuntu 操作系统,以防有人和你有同样的担忧:

    我已经按照post from Reddit 中的某些步骤进行操作,我可以证明这可以使 SPA 在具有正确路由的 Apache Web 服务器中运行。

    引用:

    1) 在位于etc/apache2/apache2.conf 中,我将AllowOverride 转为All。我还在文件中添加了 Servername localhost。 (不知何故我跳过了最后一句话,但最后还是很好用)

    <Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    

    2) 在/etc/cloud/templates 中找到的hosts.debian.tmpl 文件中,我将127.0.0.1 &lt;yourdomain.com&gt; 添加到其他相似ip 所在的文件中。

    127.0.0.1 yourdomain.com
    

    3) 我跑了sudo a2enmod rewrite。然后我通过service apache2 restart 重新启动了 apache 服务器。这会打开 mod_rewrite。

    最后在我的项目文件夹 /var/www/html 中,除了我的 index.html 文件,我创建了一个 .htaccess 文件并添加了以下内容:

    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^.*$ / [L,QSA]
    

    结束引用

    假设您已运行 npm run build,然后将 build 文件夹中的所有内容复制到您的公共目录,这应该可以工作。

    当我第一次开始 web 开发时,我并不确定我的 VirtualHost 配置是否正确,所以我通常会先制作一个虚拟的 index.html,例如 Hello World 示例。当我确认可以在浏览器中看到 Hello World(这意味着我的 VirtualHost 配置正确)后,我将 build 文件夹的内容转储到虚拟 index.html 所在的位置。

    希望这对您现在和对我一样有帮助!

    【讨论】:

      猜你喜欢
      • 2017-10-26
      • 2018-03-31
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 2018-01-01
      相关资源
      最近更新 更多