[英]Apache rewrite rule causes "too many redirects" for JS and CSS files
我正在使用自定义 CMS(由其他人编写)进行项目。 现有的.htaccess
文件具有一些条件和重写规则,其中之一将请求定向到index.php
文件。 该文件加载 CMS 对象,并调用一个方法来检查 URL 是否指向现有的 CMS 页面。 如果没有,用户将被重定向到 404 页面。
CMS 还允许您在基本 CMS 功能之上构建自定义模块。 通常这用于用户管理和类似的东西,但对于这个项目,客户希望能够建立一个包含数百个知识库项目的知识库,这在 CMS 中会变得一团糟。 我现在已经为这些项目构建了一个自定义模块,它们还存储了一个 slug。 我希望 URL 为/knowledgebase/items/item-slug
,但是使用现有配置,这将导致重定向到 404 页面,因为就 CMS 而言, item-slug
不会导致现有的 CMS 页面。 这是.htaccess
文件中的当前重写部分。
# Enable the rewrite engine
RewriteEngine On
RewriteBase /domain.tld
# SSL Redirect 301 transfer the current request.
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# never rewrite for existing files, and links
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
#RewriteCond %{REQUEST_FILENAME} !-d
# For Friendly URLs
RewriteRule ^knowledgebase/items/(.*)$ index.php?knowledge_item_slug=$1 # my own RewriteRule
RewriteRule ^(.*)$ index.php [L]
在 index.php 中,我添加了以下几行来检查是否需要显示自定义知识库项目
if (isset($_GET['knowledge_item_slug']) && $_GET['knowledge_item_slug'] !== '') {
include_once(__DIR__ . '/components/knowledgebase_item.php');
exit(0);
}
这工作正常,转到knowledgebase/items/test
按应有的方式加载测试项目。 但是,添加此规则后,在硬重新加载(清除缓存)后将无法再找到 CSS 和 JS 文件,并导致控制台中出现net::ERR_TOO_MANY_REDIRECTS
错误。
我已将规则修改为RewriteRule ^kennisbank/items/(.*)$ index.php?knowledge_item_slug=$1 [C]
(基本上只是添加了[C]
标志),现在项目详细信息页面有效,但任何其他页面导致错误The requested URL /domain.tld/page was not found on this server.
我也试过将RewriteRule ^(.*)$ index.php
放在我自己的 RewriteRule 之上(显然没有[L]
标志),但是我自己的一个根本不起作用。
我对 Apache 重写不太熟悉,知道是什么导致了这个问题吗?
问题是在检查RewriteCond
非文件和非目录后,您有 2 个RewriteRule
规则。 只有紧接的下一个RewriteRule
会受到一个或多个RewriteCond
影响,因此最后一条规则在没有任何条件的情况下执行,将包括 css/js/images 在内的每个请求路由到index.php
。
你可以像这样拥有你的 .htaccess:
# Enable the rewrite engine
RewriteEngine On
RewriteBase /domain.tld
# SSL Redirect 301 transfer the current request.
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
# never rewrite for existing files, and links
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]
# For Friendly URLs
RewriteRule ^knowledgebase/items/(.*)$ index.php?knowledge_item_slug=$1 [L,NC,QSA]
RewriteRule ^ index.php [L]
Do-nothing规则RewriteRule ^ - [L]
将跳过该行以下的任何规则,用于上述条件,即非文件和非目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.