社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  NGINX

nginx“try_files”中的cascade index.php

nice ass • 4 年前 • 404 次点击  

在Apache中,可以使用 .htaccess

文件夹结构示例:

/Subdir
/index.php
/.htaccess   

/Subdir
/Subdir/.htaccess
/Subdir/index.php

如果我进入 /something 它将重定向到根index.php,如果我访问 /Subdir/something 它将重定向到 Subdir/index.php

这也可以在nginx中完成吗? 它应该是可能的,因为在nginx文档中它说 If you need .htaccess, you’re probably doing it wrong :)

我知道如何将所有内容重定向到root index.php:

location / {
  try_files $uri $uri/ /index.php?$query_string;
}

但是如何在每个父目录中检查index.php直到 / ?

编辑:

我发现这些规则是我想要的:

location / {
  try_files $uri $uri/ /index.php?$query_string;
}

location /Subdir{
  try_files $uri $uri/ /Subdir/index.php?$query_string;
}

但是有没有一种方法可以让它抽象化,比如

location /$anyfolder{
  try_files $uri $uri/ /$anyfolder/index.php?$query_string;
} 

?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/37983
 
404 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Dayo
Reply   •   1 楼
Dayo    5 年前

这个 index 指令应该处理大部分问题

server {
    index index.php;
    ...
} 

如果您的设置要求使用try_文件,那么这应该对您有用:

location / {
    try_files $uri $uri/ $uri/index.php?$query_string =404;
}

您还可以捕获位置并将其用作变量:

location ~ ^/(?<anyfolder>) {
    # Variable $anyfolder is now available
    try_files $uri $uri/ /$anyfolder/index.php?$query_string =404;
}

编辑

我从您的评论中看到,您希望首先尝试主题文件夹的index.php文件,如果主题文件夹中没有,请转到根文件夹中的文件。

为此,你可以尝试一下……

location / {
    try_files $uri $uri/ $uri/index.php$is_args$args /index.php$is_args$args;
}

注: $is_args$args 比…好 ?$query_string 如果有机会,可能不会有争论。

编辑2

可以。得到了赏金,但一直觉得我错过了什么,你的问题实际上没有得到解决。在阅读和重读之后,我想我终于完全理解了你的疑问。

要检查目标文件夹中的index.php。如果找到,将执行此操作。如果找不到,继续检查目录树上的父文件夹,直到找到一个(可能是根文件夹)。

我在上面的“编辑”中给出的答案只是跳到根文件夹,但您要先检查中间的文件夹。

未测试,但可以尝试递归regex模式

# This will recursively swap the parent folder for "current"
# However will only work up to "/directChildOfRoot/grandChildOfRoot"
# So we will add another location block to continue to handle "direct child of root" and "root" folders
location ~ ^/(?<parent>.+)/(?<current>[^\/]+)/? {
    try_files /$current /$current/ /$current/index.php$is_args$args /$parent;
}

# This handles "direct child of root" and "root" folders
location / {
    try_files $uri $uri/ $uri/index.php$is_args$args /index.php$is_args$args;
}