[英]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.