【问题标题】:reactJS routing, errors 500 & .htaccess: rewrite rules not working on sub-routesreactJS 路由,错误 500 和 .htaccess:重写规则不适用于子路由
【发布时间】:2021-06-01 22:02:44
【问题描述】:

我基于create-react-app构建了一个react应用。

在 package.json 中,我使用了 '.'作为主页的值:

{
    ...
    "homepage": ".",
    ...
}

但是在部署时,我有 500 个服务器错误;其中I fixed by adding some htaccess stuff;在重写规则的顶部强制使用 HTTPS:

<IfModule mod_rewrite.c>

    #force HTTPS
    RewriteEngine On 
    RewriteCond %{HTTPS} off 
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    #fix 500 errors
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule . /$1 [L]

</IfModule>

这似乎适用于像这样的网址

mywebsite.com

mywebsite.com/component

但不适用于像

这样的子路由

mywebsite.com/component/something

这些确实会引发各种错误,例如

Uncaught SyntaxError: Unexpected token '

我注意到在服务器上打开这个文件(或任何资产)实际上会加载 index.html 文件;因为.htaccess的重写规则,我想。

我应该如何更新我的 .htaccess 文件,以便它只将“主”请求重定向到 index.html 而不是资产?

谢谢!

【问题讨论】:

  • RewriteConds 检查请求的内容是否与物理上存在的文件、文件夹或符号链接不匹配 - 因此,如果您在这里谈论静态资产,这应该不会影响它们。不清楚您希望 $1 是什么,但您的 RewriteRule 甚至没有捕获任何东西?
  • 这是我复制/粘贴的东西。对重写规则不太了解...但是请查看v2.spiff-radio.org/wizard/…,并检查控制台:您会看到资产未正确加载。感谢您的帮助!
  • 尝试制定最后一条规则RewriteRule . /index.html [L],看看是否有任何改变。
  • 嗨,我做了测试;也不行。

标签: reactjs apache .htaccess mod-rewrite routes


【解决方案1】:

我终于通过更改解决了它

"homepage": ".",

"homepage": "",

在我的 package.json 中。

还在这篇文章中发现了有关该问题的有趣信息:An elegant solution of deploying React app into a subdirectory,他们建议在其中添加

<base href="%PUBLIC_URL%/">

index.html&lt;head/&gt; 部分中;但在我的情况下,它似乎没有这条线。

作为记录,this gist 也很有用。

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2013-01-04
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    相关资源
    最近更新 更多