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

时间:2015-06-07 12:11:01

标签: php apache .htaccess

我正在尝试在php .htaccess文件中的ErrorDocument中制作404,500个页面,如果给出它可以正常工作

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

但我不想在这里对网址进行硬编码,而是想要动态获取根网址的名称,这样我就不会随着主机名的变化而一次又一次地更改它。

基本上我想得到这样的根网址:http://localhost/project可以更改为http://www.example1.com/projecthttp://www.example2.com/project等。此网址必须来自项目根文件夹。

这将动态变为:

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

请帮忙吗?

2 个答案:

答案 0 :(得分:4)

提问者要求不正确。所有他写的东西

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 with code

中的htacces来完成
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule ^  errordocs/404.html [L]

如果AllowOverride设置为All(默认值),它将起作用。

只有在这种情况下响应的问题是200而不是404

答案 1 :(得分:1)

基于conversation you had,您希望在将项目移动到另一个名称不同的文件夹时不必更改错误文档的路径。

首先,使用ErrorDocument时无法使用变量。您提供的路径必须是静态的。您指定的路径必须是外部URL(在这种情况下,您的浏览器将被重定向)或相对于文档根目录的文件(即localhost)。

不幸的是,ErrorDocument无法找到相对于当前目录的文件(即project)。执行此操作的唯一合理方法是删除前导斜杠,但这会导致Apache将其呈现为浏览器中的字符串。

这为我们带来了唯一的其他解决方案:mod_rewrite。然而,使用它的唯一问题是它在映射管道的早期处理可能允许其他模块(例如mod_proxy)影响进程。 / p>

那就是说,您可以尝试以下方法:

<强> /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

此文件将以.htaccess发送404标头,但无法做到这一点。

<?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>