繁体   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