繁体   English   中英

放置在子文件夹中时,.htaccess 中的 ErrorDocument 重定向

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM