如何使用 try_files 从 url 中删除带有 nginx 的子目录
How to remove subdirectory with nginx from urls using try_files
一整天我都在努力寻找特定问题的解决方案。
我的结构如下所示:
location / {
try_files $uri $uri/ /index.php?$uri&$args;
}
现在子目录的所有 php 文件也应该在 /index.php 中解析。
location /subdir/ {
try_files $uri $uri/ /index.php?$uri&$args;
}
当我点击 /subdir/thread.php?t=123
时,$uri
包含 /subdir/thread.php?t=123
。但我想在 $uri
中只有 /thread.php?t=123
(没有子目录)。
这可能吗?我不想使用重写,因为我将此脚本用于重定向脚本。
您需要使用正则表达式来捕获 URI
中要传递给 /index.php
的部分。使用 location
或 rewrite
来实现这一点。
使用正则表达式 location
:
location ~ ^/subdir(/.*)$ {
try_files $uri $uri/ /index.php?&$args;
}
location ~ \.php$ { ... }
正则表达式 location
块按顺序计算,因此块在配置文件中的位置很重要。
要将子目录中的 .php
文件发送到 /index.php
,您需要将此 location
块放在 上方 location \.php$
块。
详情见this document。
使用命名的 location
和 rewrite
:
location ^~ /subdir/ {
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite ~/subdir(/.*)$ /index.php? last;
}
^~
运算符确保子目录中的 .php
文件也被发送到 /index.php
.
rewrite
自动附加原始查询字符串。有关详细信息,请参阅 this document。
一整天我都在努力寻找特定问题的解决方案。
我的结构如下所示:
location / {
try_files $uri $uri/ /index.php?$uri&$args;
}
现在子目录的所有 php 文件也应该在 /index.php 中解析。
location /subdir/ {
try_files $uri $uri/ /index.php?$uri&$args;
}
当我点击 /subdir/thread.php?t=123
时,$uri
包含 /subdir/thread.php?t=123
。但我想在 $uri
中只有 /thread.php?t=123
(没有子目录)。
这可能吗?我不想使用重写,因为我将此脚本用于重定向脚本。
您需要使用正则表达式来捕获 URI
中要传递给 /index.php
的部分。使用 location
或 rewrite
来实现这一点。
使用正则表达式 location
:
location ~ ^/subdir(/.*)$ {
try_files $uri $uri/ /index.php?&$args;
}
location ~ \.php$ { ... }
正则表达式 location
块按顺序计算,因此块在配置文件中的位置很重要。
要将子目录中的 .php
文件发送到 /index.php
,您需要将此 location
块放在 上方 location \.php$
块。
详情见this document。
使用命名的 location
和 rewrite
:
location ^~ /subdir/ {
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite ~/subdir(/.*)$ /index.php? last;
}
^~
运算符确保子目录中的 .php
文件也被发送到 /index.php
.
rewrite
自动附加原始查询字符串。有关详细信息,请参阅 this document。