nic*_*ass 5 apache .htaccess nginx url-rewriting
在 Apache 中,可以将所有内容重定向到最近的 index.php,使用 .htaccess
示例文件夹结构:
/Subdir
/index.php
/.htaccess
/Subdir
/Subdir/.htaccess
/Subdir/index.php
Run Code Online (Sandbox Code Playgroud)
如果我访问/something它会重定向到根 index.php,如果我访问/Subdir/something它会重定向到Subdir/index.php
这也可以在nginx中完成吗?这应该是可能的,因为在 nginx 文档中它说If you need .htaccess, you’re probably doing it wrong:)
我知道如何将所有内容重定向到根 index.php:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
Run Code Online (Sandbox Code Playgroud)
但是如何在每个父目录中检查 index.php 直到/?
编辑:
我发现这些规则可以满足我的要求:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location /Subdir{
try_files $uri $uri/ /Subdir/index.php?$query_string;
}
Run Code Online (Sandbox Code Playgroud)
但是有没有办法让它抽象,比如
location /$anyfolder{
try_files $uri $uri/ /$anyfolder/index.php?$query_string;
}
Run Code Online (Sandbox Code Playgroud)
?
索引指令应该解决大部分问题
server {
index index.php;
...
}
Run Code Online (Sandbox Code Playgroud)
如果您的设置要求使用 try_files,那么这应该适合您:
location / {
try_files $uri $uri/ $uri/index.php?$query_string =404;
}
Run Code Online (Sandbox Code Playgroud)
您还可以捕获位置并将其用作变量:
location ~ ^/(?<anyfolder>) {
# Variable $anyfolder is now available
try_files $uri $uri/ /$anyfolder/index.php?$query_string =404;
}
Run Code Online (Sandbox Code Playgroud)
我从您的评论中看到,您想首先尝试主题文件夹的 index.php 文件,如果主题文件夹中没有该文件,则继续访问根文件夹中的文件。
为此,你可以尝试类似...
location / {
try_files $uri $uri/ $uri/index.php$is_args$args /index.php$is_args$args;
}
Run Code Online (Sandbox Code Playgroud)
注意:比有可能不发生争论$is_args$args要好。?$query_string
好的。得到了赏金,但一直觉得我错过了一些东西,而且你的问题实际上没有得到解决。经过阅读和重读,我现在想我终于完全理解了你的问题。
您想要检查目标文件夹中是否有index.php。如果找到,这将被执行。如果未找到,请继续检查目录树中的父文件夹,直到找到一个(可能是根文件夹)。
我在上面的“编辑”中给出的答案只是跳转到根文件夹,但您需要首先检查中间文件夹。
未经测试,但您可以尝试递归正则表达式模式
# 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1045 次 |
| 最近记录: |