【问题标题】:Rewriting to subdirectory and then to React's index.html using root .htaccess重写到子目录,然后使用 root .htaccess 重写到 React 的 index.html
【发布时间】:2021-08-05 01:06:08
【问题描述】:

我正在尝试创建位于根网络服务器目录中的 .htaccess 文件。在根目录下,还会有多个名为 backend/ 和 frontend/ 的目录(它们的名称是可变的)。

当前树可能如下所示:

/
  .htaccess
  frontend/
      static/
      index.html
      manifest.json
  backend/
      files/
      index.php
  other/

由于前端 (React) 和后端 (PHP) 由其他人完成并使用 CI 部署,因此我无法控制这两个目录中的文件和文件夹。

我试图用 .htaccess 文件完成的是:

  1. 重写(不重定向)到/** 并且本身不存在的所有内容到/frontend/**
  2. /frontend/** 中不存在的所有内容都应返回 /frontend/index.html

这里有一些例子:

  • / 变为 /frontend/ (#1)
  • /index.html 变为 /frontend/index.html (#1)
  • /manifest.json 变为 /frontend/manifest.json (#1)
  • /static/script.js 变为 /frontend/static/script.js (#1)
  • /module 变为 /frontend/index.html(#1 和 #2)
  • /backend/** 不会因为目录存在而被重写
  • /other/** 不会因为目录存在而被重写

我当前的文件如下所示:

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteBase /

   # Rewrite root directory to frontend
   RewriteCond %{REQUEST_URI} ^/$
   RewriteRule ^(.*)$ /frontend/index.html [NC,L,QSA]

   # Rewrite non-existent files and folders to frontend
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_URI} !^/frontend/
   RewriteRule ^(.*)$ /frontend/$1 [NC,L,QSA]
</IfModule>

主要是无法将/module重写为/frontend/index.html
我应该如何继续?

【问题讨论】:

  • 添加重定向到 /frontend/index.html 的 ErrorDocument 404 怎么样?

标签: apache .htaccess url


【解决方案1】:

像这样:

RewriteEngine on
RewriteBase /

# skip backend/ and other/ directories
RewriteRule ^(?:backend|other)/ - [L,NC]

# forward these known paths to /frontend/
RewriteRule ^(index\.html)$ /frontend/$1 [L,NC]

# rewrite an alphanumeric URI that is non-file/dir to /frontend/index.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^\w+/?$ /frontend/index.html [L]

# Rewrite non-existent files and folders to frontend
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/frontend/ [NC]
RewriteRule ^(.*)$ /frontend/$1 [L]

【讨论】:

  • 感谢您的回答!但是,我事先不知道模块的名称(“模块”只是一个例子),也不知道前端目录中的文件名(它们是由 React 的 NPM 动态生成的)。
  • 我也想过,但问题是frontend/ 部署的 CI 会覆盖里面的所有内容。我只能使用放在根目录下的.htaccess
  • 这仍然假设我知道manifest.jsonstatic/scripts.js 将会出现。 CI 部署的前端对我来说是一个黑匣子。此外,它不会将 React 应用所在的子模块(module/module2/ 等)重写为 index.html
  • 查看更新。它确实重写了moduleN//static/script\.js 等,因为这不是站点根目录中的文件或目录,因此它将由重写为/frontend/moduleN 的最后一条规则处理。
  • 谢谢!我看到它满足 #1 - 它被重写为 frontend/。但是,#2 不起作用。我需要将模块(它的名称可以是任何字母数字)重写为 React 应用程序所在的 index.html(resp.frontend/index.html)。
猜你喜欢
  • 2012-05-06
  • 2023-03-19
  • 2014-03-29
  • 2010-10-26
  • 1970-01-01
  • 2013-05-11
  • 2012-05-25
  • 2012-01-26
  • 1970-01-01
相关资源
最近更新 更多