return
rewrite
…… last
除了上面的两个指令之外的任何操作都有可能导致不可预测的效果甚至可能是SIGSEGV错误(可能出现内存错误导致程序异常终止)。
需要注意的是:
if
指令的执行结果是一致的,也就是说相同的两个请求操作,不可能会出现一个成功但是另一个失败的情况。这就意味着只要经过足够合适的测试以及我们对相应操作的足够了解,
if
指令是
“可以”
被使用的。这个建议对于其他的指令也是同样适用的。
很多情况下我们是没办法避免使用if指令的,例如当我们需要判断某个变量是否等于某个值或者包含某个字段的时候,就会需要用到if指令:
|
if ($request_method = POST ) { return 405; } if ($args ~ post=140){ rewrite ^ http://example.com/ permanent; }
|
try_files
指令、“return …”指令或者“rewrite … last”指令用来替代if指令。在某些条件允许的情况下,也可以把
if
指令移动到
server
块的层级,此时的if指令是可以安全使用的,因为这里只有其他的rewrite模块指令能被使用(原因下文会解释)。
当然对于一些需要使用
if
指令来判断返回
4xx
和
5xx
之类的异常代码响应页面或者是操作也可以尝试使用
return
指令搭配
error_page
指令来保证安全,例如下面的这个例子:
|
location / { error_page 418 = @other; recursive_error_pages on;
if ($something) { return 418; }
... }
location @other { ... }
|
此外,在某些情况下使用一些嵌入的脚本模块(如lua,
embedded perl
, 或者是其他的
ngx第三方模块
)来完成一些较负责的逻辑操作和判断也不失为一个好主意。
NGINX development mailing list
.
工作原理
和流程
事先进行足够的测试以确保能够正常工作
You were warned.