在.htaccess中动态获取站点根主机名


Get the site root host name dynamically in .htaccess

我试图使404,500等页面在ErrorDocument在php .htaccess文件,它工作良好,如果给

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

但是我不想硬编码这里的url,相反,我想动态地获得根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

但是他真正想要的是:当把站点从project folder移到project1时,他不应该改变规则

我认为可以通过在/project中放置htaccess来完成,代码为

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>