簡體   English   中英

在.htaccess中動態獲取站點根主機名

[英]Get the site root host name dynamically in .htaccess

我試圖在php .htaccess文件中的ErrorDocument中制作404,500個頁面,如果給它,它工作正常

ErrorDocument 404 http://localhost/project/errordocs/404.html

但我不想在這里硬編碼網址,而是我想動態獲取根URL網站名稱,以便我不會在主機名更改時一次又一次地更改它。

基本上我想得到這樣的根URL: http://localhost/project可以更改為http://www.example1.com/projecthttp://www.example2.com/project等。這個url必須來自項目根文件夾。

這將動態變為:

ErrorDocument 404 http://localhost/project/errordocs/404.html
ErrorDocument 404 http://www.example1.com/project/errordocs/404.html
ErrorDocument 404 http://www.example2.com/project/errordocs/404.html

有什么幫助嗎?

提問者問不正確。 所有他寫的東西

ErrorDocument 404 http://localhost/project/errordocs/404.html
ErrorDocument 404 http://www.example1.com/project/errordocs/404.html
ErrorDocument 404 http://www.example2.com/project/errordocs/404.html

可以通過

ErrorDocument 404 /project/errordocs/404.html

但他真的想要:在將網站從項目文件夾移動到project1時,他不應該改變規則

我認為可以通過放置在/ project中的htacces代碼完成

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule ^  errordocs/404.html [L]

如果AllowOverride設置為All(默認值),它將起作用。

只有在這種情況下響應的問題是200但不是404

根據對話 ,您希望在將項目移動到具有不同名稱的另一個文件夾時不必更改錯誤文檔的路徑。

首先,使用ErrorDocument時不能使用變量。 您提供的路徑必須是靜態的。 您指定的路徑必須是外部URL(在這種情況下,您的瀏覽器將被重定向)或相對於文檔根目錄的文件(即localhost )。

不幸的是, ErrorDocument將無法找到相對於當前目錄(即project )的文件。 執行此操作的唯一合理方法是刪除前導斜杠,但這會導致Apache將其呈現為瀏覽器中的字符串。

這將我們帶到唯一的其他可能的解決方案: mod_rewrite 然而,使用它的唯一問題是它在映射管道的早期處理,可能允許其他模塊(例如mod_proxy)影響該過程

也就是說,您可以嘗試以下方法:

/project/.htaccess

RewriteEngine on

# Determine if the request does not match an existing file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# If so, send the request to the applicable file, relative to this directory
RewriteRule ^ errordocs/404.php [L]

# Per your comment and suggested edit, add the following.
# Note: This should not make any difference as mod_rewrite and PHP should
# already handle the error document.
ErrorDocument 404 /errordocs/404.php

/project/errordocs/404.php

此文件將發送404標頭,因為.htaccess將無法執行此操作。

<?php header("HTTP/1.0 404 Not Found"); ?>

<h1>Sorry, we couldn't find that...</h1>
<p>The thing you've requested doesn't exist here. Perhaps it flew away?</p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM