Rud*_*die 2 url-rewriting nginx
我正在努力处理 nginx 配置。我有一个server块,我希望所有请求都转到index.php?tags=$uri,除非$uri存在(如index.php?a=b或/?a=b)。
我期望:
try_files $uri index.php?tags=$uri;
Run Code Online (Sandbox Code Playgroud)
但是,不,那太简单了。这不适用于/?a=b,显然没有找到,所以它指向index.php?tags=/
也许如果我明确包含一个index,这是合理的:
index index.php;
Run Code Online (Sandbox Code Playgroud)
没有。没有骰子。全面相同的确切结果。
也没有$args、$request_uri或组合。也不是它:
try_files $request_uri/index.php $request_uri index.php?tags=$request_uri; // now I'm just guessing
Run Code Online (Sandbox Code Playgroud)
阿帕奇总是知道我的意思。为什么nginx没有?我想要这些重定向(不带redirect或if):
/ => /index.php
/index.php => /index.php
/index.php?a=b => /index.php?a=b
/?a=b => /index.php?a=b
/foo => /index.php?tags=foo (or /index.php?tags=/foo)
/foo/bar => /index.php?tags=foo/bar (or /index.php?tags=/foo/bar)
/foo?bar=yes => /index.php?tags=/foo%3Fbar%3Dyes
Run Code Online (Sandbox Code Playgroud)
我希望在重定向时对查询字符串进行编码,而不是对路径进行编码,但实际上这并不那么重要。
(我也不明白 $uri 和 $request_uri 之间的实际区别。它们似乎一半时间都在做同样的事情。但那是另一天的事了。)
非常感谢。
我通过以下配置片段实现了预期的结果:
location = / {
index index.php;
}
location / {
try_files $uri /index.php?tags=$request_uri;
}
Run Code Online (Sandbox Code Playgroud)
try_files尝试...文件。当您/使用它进行查找时,您会搜索具有相同名称的文件,它不会被解释为“查找索引文件”。index做那个工作。因此,您需要将这种特殊情况与默认的后备位置分开。
最好的部分是您的最后一个愿望:参数甚至不会被编码,因为它们不需要(只有 URI 的第一个问号是相关的,因为后面的所有内容都是参数)。
请注意使用$request_uri(包含所请求的 URI,带参数,但不会规范化/清理它)而不是规范化$uri(清理 URI 并删除参数)。因此你最终可能会得到:
///foo?bar=yes => index.php?tags=///foo?bar=yes
Run Code Online (Sandbox Code Playgroud)
location = / {
index index.php;
}
location / {
try_files $uri /index.php?tags=$uri?$args;
}
Run Code Online (Sandbox Code Playgroud)
生产:
///foo?bar=yes => index.php?tags=/foo?bar=yes
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5714 次 |
| 最近记录: |