apache - 设置自定义 DocumentRoot 时,将子文件夹中所有存在和不存在的页面和文件夹重定向到一页

标签 apache .htaccess mod-rewrite url-rewriting document-root

我有下一个文件结构:

.htaccess
index.php
public/
├─ v1/
│  ├─ .htaccess
│  ├─ index.php
├─ index.php

我已将服务器级别的文档根目录设置为 public 子文件夹,以便将其从 URL 中删除。

我需要将 url 中包含 v1 的所有请求重定向到 v1/index.php

我的根.htaccess:

RewriteEngine On
RewriteCond %{REQUEST_URI} !public/
RewriteRule (.*) /public/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]

v1/.htaccess:

RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} !-d  [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ index.php [QSA,L]

预期行为:

不存在的 https://example.com/v1/test 页面应重定向到 https://example.com/v1/

我得到了什么:

Not Found
The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

我很确定问题出在第二个 .htaccess 中。我还怀疑自定义文档根在这里也可能是一个问题。

最佳答案

尝试以下列方式获得您的根 .htaccess 一次,然后尝试一下并删除您的内部 .htaccess(尽管在本地系统中保留它的备份,但系统上没有它)。在测试 URL 之前清除浏览器缓存。

RewriteEngine ON

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} !\s/public(?:/\S*)*\s [NC]
RewriteCond %{THE_REQUEST} !\s/v1(?:/\S*)*\s [NC]
RewriteRule ^(.*)/?$ /public/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} !\s/v1(?:/\S*)*\s [NC]
RewriteRule ^([^\.]+)$ $1.php [NC,L]

RewriteCond %{THE_REQUEST} !\s/v1/?\s [NC]
RewriteRule ^(v1)/.+/?$ /$1/? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^v1/?$  public/v1/index.php [QSA,L]

注意:将在早上添加详细的解释,因为对我来说太晚了。

关于apache - 设置自定义 DocumentRoot 时,将子文件夹中所有存在和不存在的页面和文件夹重定向到一页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74130540/

相关文章:

.htaccess - htaccess 在 RewriteCond 中使用 OR 条件

apache - htaccess 文件规则

php - htaccess 重写本地主机的更改

apache - 处理蠕虫 URL 的最佳实践

java - 需要第三方框架的 Multi-Tenancy 功能

apache - 如何在 mod_proxy_ajp 的 apache HTTP 服务器中覆盖方案和 is_ssl

regex - .htaccess 正则表达式差异/优点/缺点

apache - 多个重写条件 : How to chain them before a set of rules?

apache - .htaccess:将根 url 重定向到子目录,但保留根 url

apache - 用 RewriteLock 理解 Apache RewriteMap