简体   繁体   English

静默重写URL到NGINX中的子子目录

[英]Silently Rewrite URL to sub-sub-directory in NGINX

I am wondering if someone can please help me with something that I am racking my brain with.我想知道是否有人可以帮助我解决我正在绞尽脑汁的事情。 I have a folder structure like this;我有这样的文件夹结构;

/var/www/<user>/<user>/

So to see the files currently with NGINX I need to naviagte to;因此,要查看当前使用 NGINX 的文件,我需要导航到;

https://<host>/<user>/<user>

What I want to do is make it so I can navigate to the following and it is re-written silently in the backend.我想做的是让它导航到以下内容,并在后端默默地重写它。

https://<host>/<user>/

To achieve this, I have written the following rule为此,我编写了以下规则

location ~ ^/(.*)/(.*)$ {
    index index.html;
    try_files $uri /$1/$uri/index.html /$1/$uri;
}

It seemed to work once but since it unfortunately keeps rewriting in a continuous loop.它似乎工作了一次,但不幸的是它一直在连续循环中重写。 I've tried a few things and understand why it loops but I cannot work out how to stop it.我已经尝试了一些事情并理解它为什么会循环,但我无法弄清楚如何阻止它。

Now, you may be wondering why have this folder structure.现在,您可能想知道为什么会有这种文件夹结构。 It's a long story but basically I want a user to only have access to their files and with Chroot (for sftp) the root dir must be owned by root so it needs a subdirectory to make it work due to permissions.这是一个很长的故事,但基本上我希望用户只能访问他们的文件,并且使用 Chroot(对于 sftp),根目录必须由 root 拥有,因此它需要一个子目录才能使其由于权限而工作。

So if anyone has this issue in future, the problem what that the first match ($1) was matching incorrectly, it contained everything in between the slashes.因此,如果将来有人遇到此问题,那么第一个匹配项($1)匹配不正确的问题,它包含斜杠之间的所有内容。 So it would match like this;所以它会像这样匹配;

/<user>/
$1 = <user>

/<user>/<subdir>
$1 = /<user>/<subdir>/

/<user>/<subdir>/<file>
$1 = /<user>/<subdir>/

To fix this so that $1 was always only the first slash part I changed the NGINX config to this:为了解决这个问题,使 $1 始终只是第一个斜杠部分,我将 NGINX 配置更改为:

location ~ /([^/]*)/(.*)?$ {
    try_files $uri /$1/$1/$2 /$1/$1/$2/index.html /$1/$1/index.html;
}

This will match like the following:这将匹配如下:

/<user>/
$1 = <user>

/<user>/<subdir>
$1 = <user>

/<user>/<subdir>/<file>
$1 = <user>

Now it all matches correctly and works fine.现在一切都正确匹配并且工作正常。 I hope that this someday helps someone else with the same issue.我希望有一天这可以帮助其他有同样问题的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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