在Apache服务器上配置React路由器的htaccess文件

fquxozlt  于 2022-12-04  发布在  Apache
关注(0)|答案(1)|浏览(133)

我已经将一个带有React Router的React应用程序部署到我的Bluehost服务器上,并且需要配置htaccess文件,将我所有的路由URL(/portfolio、/about等)重定向到index.html,而不是尝试从服务器上获取一个新文件并抛出404。
我读过无数类似的问题,其中的解决方案似乎是添加到您的htaccess文件:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

我试过了,但是当我试图直接访问我的网站的任何页面,而不是主页时,我仍然得到404。我想知道是否有其他东西在我现有的htaccess文件中,阻止上述代码工作?
这里已经有一些来自Bluehost的代码,我看到了另一个IfModule语句,所以我想知道这个语句是否覆盖了第一个语句。但是我害怕编辑它,因为它清楚地写着“不要编辑”。下面是我的完整htaccess代码:

Header always set Content-Security-Policy: upgrade-insecure-requests

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php74” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php74 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.

# END WordPress

有什么想法吗?我已经仔细检查了我的BrowserRouter是否设置正确,也尝试了一些其他的htaccess配置。我想避免使用HashRouter或Node,如果可能的话,但我越来越沮丧。如果需要的话,我也可以提供我的React代码,但我很确定错误不是与React设置有关。

n7taea2i

n7taea2i1#

您可以在/etc/apache/sites-available文件夹中创建一个虚拟主机文件,并添加以下内容:

<VirtualHost *:8080>
   ServerName example.com
   DocumentRoot /var/www/httpd/example.com

  <Directory "/var/www/httpd/example.com">
    ...

    RewriteEngine on
    # Don't rewrite files or directories
    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>

这对我很有效

相关问题