自动索引会切断目录路径的末尾;需要解决方法

自动索引会切断目录路径的末尾;需要解决方法

我正在尝试使用 nginx 设置一种共享主机,其中每个用户都有一个public_html目录。对 的请求/~username别名为/home/domain-users/username/public_html。问题是,我还想启用自动索引。将下面的配置添加到服务器块中后,对特定文件(如 )的请求可以/~username/test.txt正常工作;它们别名为/home/domain-users/username/public_html/test.txt。但是,当尝试请求/~username或 时~/username/,我得到 404 并/var/log/nginx/error.log显示自动索引出于某种原因试图列出 中的文件/home/domain-users/username/public_htm(请注意缺少“l”:路径被截断。)

由于能够/~username以不带尾部斜杠的方式访问目录并不重要,因此我尝试$public_html_path/try_files指令中删除。然后,即使在请求时/~username/,也不会调用 autoindex。也许 autoindex 需要文字尾部斜杠try_files才能运行。

# For requests to "/~username" without a trailing slash
set $public_html_path "";
# Lazy quantifier at the end allows processing requests to "~/username". We add the trailing slash later in try_files
location ~ ^\/\~(?<user_home_folder>[^\\n\/]+)(?<public_html_path>\/.*)?$ {
    alias /home/domain-users/$user_home_folder/public_html;
    autoindex on;
    try_files $public_html_path $public_html_path/ =404;
}

我的研究成果很少,最接近的是这个 StackOverflow 问题。由于这似乎是 NGINX 中的一个不太可能修复的错误(上一次评论是在一年前),我正在寻找一种解决方法。使用指令root代替将alias是完美的,但 autoindex 会删除/~username/URI 的关键部分,认为它列出的文件位于 Web 根目录中,因为从某种意义上说,它们确实位于 Web 根目录中。即使是黑客式的解决方法也会非常受欢迎……谢谢!

答案1

当使用alias正则表达式时location,您需要重建alias值中的整个路径名。请参阅这个文件了解详情。

location ~ ^/~(?<user_home_folder>[^/]+)(?<public_html_path>/.*)?$ {
    alias /home/domain-users/$user_home_folder/public_html$public_html_path;
    autoindex on;
}

try_files一起使用alias可能会引起并发症,因为这个问题try_files。但是,默认行为实际上与您问题中的陈述相同。

相关内容