我希望我的.htaccess檔案發生一些非常具體的事情,但我不確定這是否可能。我希望將鏈接example.com/ExampleFile.txt轉發到example.com/Other/ExampleFile.txt(因為我即將將所有內容移至“其他”目錄以清理根目錄。)然后如果在“其他”目錄中未檢測到檔案,我想用戶最初鍵入 ( example.com/ExampleFile.txt) 的路徑,將通過該路徑發送到subdomain.example.com/ExampleFile.txt。
請讓我知道這是否可行,如果可以,我需要將哪些代碼添加到我的.htaccess檔案中?請注意,我使用的是 LiteSpeed,而不是 Apache。
我已經可以使用以下代碼完成最后一部分:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ https://subdomain.example.com%{REQUEST_URI} [R=302,L]
提前致謝!
uj5u.com熱心網友回復:
在現有重定向之前添加以下重寫,以測驗請求是否映射到/Other子目錄中的檔案,然后再重寫請求(如果是):
# Rewrite request to the "/Other" subdirectory
# - only if the request maps to a file or directory there
RewriteCond %{DOCUMENT_ROOT}/Other/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/Other/$1 -d
RewriteRule (. ) Other/$1 [L]
注意:如果相同的檔案存在于兩個根目錄中(或者更確切地說,在“/Other”子目錄之外),那么/Other子目錄中的檔案將獲勝。
如果您只想重寫實際檔案而不是目錄,則洗掉第二個條件和OR標志。
大概所有對根的請求都應該被重寫/Other/(因為它作為一個目錄存在)所以這應該無條件地執行:
# Rewrite root to "/Other/"
RewriteRule ^$ /Other/ [L]
并且您現有的重定向subdomain.example.com遵循這些重寫。
更新:
但我確實注意到,如果沒有使用此方法的檔案擴展名,我將無法訪問檔案。[...] 任何想法為什么在使用此方法時我無法訪問沒有擴展名的檔案?我有一個名為
ExampleFile.txtin的檔案/Other,可以在example.com/ExampleFile.txt但不是example.com/ExampleFile.
因為在重寫 URL 之前,我們必須檢查請求的 URL 是否映射到子目錄中的檔案(或目錄)。
如果您堅持為不同型別的資源(.txt、.html、影像等)提供無擴展名 URL,那么您將需要手動檢查您允許無擴展名的每個檔案擴展名(與您已經為請求所做的方式大致相同)在規定的子目錄之外)。
例如:
# For files that already have an extension OR directories...
# NB: Directories could be requested initially with or without the trailing slash
# Rewrite request to the "/Other" subdirectory
# - only if the request maps directly to a file or directory there
RewriteCond %{DOCUMENT_ROOT}/Other/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/Other/$1 -d
RewriteRule (. ) Other/$1 [L]
# Check for ".txt" files...
RewriteCond %{REQUEST_URI} !(\.\w{2,4}|/)$
RewriteCond %{DOCUMENT_ROOT}/Other/$1.txt -f
RewriteRule (. ) Other/$1.txt [L]
# Check for ".html" files...
RewriteCond %{REQUEST_URI} !(\.\w{2,4}|/)$
RewriteCond %{DOCUMENT_ROOT}/Other/$1.html -f
RewriteRule (. ) Other/$1.html [L]
# Check for ".php" files...
RewriteCond %{REQUEST_URI} !(\.\w{2,4}|/)$
RewriteCond %{DOCUMENT_ROOT}/Other/$1.php -f
RewriteRule (. ) Other/$1.php [L]
# Check for ".jpg" files...
RewriteCond %{REQUEST_URI} !(\.\w{2,4}|/)$
RewriteCond %{DOCUMENT_ROOT}/Other/$1.jpg -f
RewriteRule (. ) Other/$1.jpg [L]
# etc.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/415609.html
標籤:
