.htaccess 重写以仅显示根 url 并隐藏 /folder 之后的所有内容

.htaccess rewrite to show only root url and hide everything after /folder

由此URL

www.example.com/error_documents/404

到这个URL

www.example.com/404

我尝试了很多不同的 .htaccess 规则,但 none 其中的规则有效。 我试图从 URL 中隐藏 /error_pages/ 文件夹部分,而不进行任何实际重定向,因为如果我编写正确的 *RewriteRule,它只会保留重复自己,我得到一个 ERR_TOO_MANY_REDIRECTS 错误,因为如果你想去一个未知的文件夹,错误文档重定向到 example.com/error_documents/404 如果我重写这是 示例。com/404,它是一个未知文件夹,因此它试图将我重定向到 /error_documents/404 页面但是htaccess 文件不断重定向到 永远循环 .

当前的 .htaccess 文件

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+error_pages/([^\s]+) [NC]
RewriteRule ^ %1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (?!^error_pages/)^(.*)$ /error_pages/ [L,NC]

这个 .htaccess 给了我永远的循环:

www.example.com/unknownfolderwww.example.com/error_documents/404www.example.com/404

这一直在重复...

我正在为 ErrorDocuments 使用 cPanel,主 .htaccess 文件是:

ErrorDocument 400 http://example.com/error_pages/400
ErrorDocument 401 http://example.com/error_pages/401
ErrorDocument 403 http://example.com/error_pages/403
ErrorDocument 404 http://example.com/error_pages/404
ErrorDocument 503 http://example.com/error_pages/503
Options -Indexes
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
ErrorDocument 400 http://example.com/error_pages/400
ErrorDocument 401 http://example.com/error_pages/401
ErrorDocument 403 http://example.com/error_pages/403
ErrorDocument 404 http://example.com/error_pages/404
ErrorDocument 503 http://example.com/error_pages/503

你不应该首先在 ErrorDocument 指令中使用绝对 URL - 这就是导致外部 (302) 重定向并暴露 [=13 的位置的原因=] 和错误文档。因此,这也会丢失有关导致错误的请求的信息。

但是,/400/401 等应引用处理请求的实际文件。例如。 /400.html/401.html 等等

您应该使用错误文档的相对根文件路径(以斜线开头),然后 Apache 将发出内部子请求,而不是重定向。

例如:

ErrorDocument 400 /error_pages/400.html
ErrorDocument 401 /error_pages/401.html
ErrorDocument 403 /error_pages/403.html
ErrorDocument 404 /error_pages/404.html
ErrorDocument 503 /error_pages/503.html

您的 /error_pages 现在对最终用户完全隐藏。

无需手动尝试将其从 URL 中删除(因为它一开始就不应该出现在 URL 中)。如果需要,您可以(可选)阻止直接访问 /error_pages 目录(注意不要阻止对错误文档的子请求)。

参考: