【问题标题】:.htaccess rewrite to show only root url and hide everything after /folder.htaccess 重写以仅显示根 url 并隐藏 /folder 之后的所有内容
【发布时间】:2021-12-14 02:59:26
【问题描述】:

来自这个网址

www.example.com/error_documents/404

到这个网址

www.example.com/404

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

当前的 .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/$1 [L,NC]

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

www.example.com/unknownfolder 到 www.example.com/error_documents/404 到 www.example.com/404

而且这一直在重复......

我将 cPanel 用于 ErrorDocuments,主 .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]

【问题讨论】:

    标签: apache .htaccess redirect mod-rewrite url-rewriting


    【解决方案1】:
    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) 重定向和暴露 /error_pages 的位置和错误文档的原因。因此,这也会丢失有关导致错误的请求的信息。

    但是,/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 目录的直接访问(注意不要阻止错误文档的子请求)。

    参考:

    【讨论】:

    • 我太笨了,没想到!感谢您的帮助,我把整个事情复杂化了。快速修复,再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 2016-06-02
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2016-02-28
    • 2013-12-24
    相关资源
    最近更新 更多