[英]ErrorDocument redirect in .htaccess when placed in subfolder
我的開發服務器 (localhost) 設置為每個網站都在它自己的子文件夾中,如下所示:
localhost
\Site1
\Site2
每個子文件夾(Site1、Site2 等)都有自己的 .htaccess:
ErrorDocument 404 /alert.php?error=404
ErrorDocument 403 /alert.php?error=403
ErrorDocument 401 /alert.php?error=401
這在實時服務器上非常有效(因為它位於網站根位置),但是,在我的本地主機開發環境中,我必須將 htacess 更新為:
ErrorDocument 404 /site1/alert.php?error=404
為了使它工作。 這意味着當我想在本地測試與上傳實時版本時,需要大量來回更新 .htaccess。
.htaccess 是否可以根據主機環境確定要使用的正確路徑?
您可以使用 mod_rewrite 計算“基本目錄”( .htaccess
文件相對於文檔根目錄所在的目錄),並在 Apache 表達式(需要 Apache 2.4.13)的幫助下在ErrorDocument
指令中使用它。
例如:
# Calculate the BASE_DIR based on the location of the .htaccess file (rel to DocumentRoot)
# For use in the ErrorDocument directive the BASE_DIR does not include the slash prefix
# eg. If in the root directory then BASE_DIR = "" (empty)
# If in /site1/.htaccess then BASE_DIR = "site1/"
RewriteCond %{REQUEST_URI}@$1 ^/(.*?)([^@]*)@\2
RewriteRule (.*) - [E=BASE_DIR:%1]
# Set ErrorDocument dynamically relative to BASE_DIR (Requires Apache 2.4.13+)
# The 2nd argument to the ErrorDocument directive must be prefixed with a slash
# in the source code itself for it to be interpreted as a local path.
ErrorDocument 404 /%{reqenv:BASE_DIR}alert.php?error=404
因此,如果.htaccess
文件位於文檔根目錄中,則ErrorDocument
設置為/alert.php?error=404
,如果在/site1
子目錄中,則將其設置為/site1/alert.php?error=404
。
旁白:當使用 PHP 時,您不需要明確地將錯誤代碼傳遞給alert.php
腳本,因為這在$_SERVER['REDIRECT_STATUS']
超全局變量中可用。 這還允許您確定是否直接調用了alert.php
腳本。
然而,最好在它自己的<VirtualHost>
定義每個站點,使用它自己的DocumentRoot
,而不是使用子目錄,並且具有與實時服務器上的本地開發完全相同的目錄/URL 結構 - 沒有混亂。 肯定還有其他地方受路徑深度不同的影響,比如客戶端鏈接到靜態資源?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.