See this conf first:
location /i/ {
add_header X-Frame-Options "SAMEORIGIN" always;
if ($uri ~ "^/i/([0-9a-zA-Z]*)([/]{0,1})$") {
set $id $1;
add_header Set-Cookie "id=$id; Max-Age=60;" always;
# return 404;
}
rewrite /i/(.*) /index.html last;
}
Then using curl http://test.com/i/abc -I
What happened about these code?
We CANNOT received any header by our definition.
What happened when uncommit return 404
?
We CAN received Set-Cookie in the response header and 404-Not found.
为什么add_header不工作了??
Interesting...
so...
See this article:
https://juejin.im/post/5c602a21f265da2dc00632be
And the official document: http://nginx.org/en/docs/http/ngx_http_headers_module.html
There could be several add_header directives. These directives are
inherited from the previous level if and only if there are no
add_header directives defined on the current level.
There really do not have any sample on the official document unless a equivocal introduction.
I am a user and really do not have time to read the source code, I think by the author's and nginx's view, the if-block is an independent context, so the code outside if and inside if is not the same level.
Fortunately, the set_header inside if haven't been destroyed, and we can return it at least. The right code is here:
if ($uri ~ "^/i/([0-9a-zA-Z]*)([/]{0,1})$") {
set $id $1;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Set-Cookie "id=$id; Max-Age=60;" always;
}
AND rewrite will jump our context into another context!
We should change the last to break to stem the jump.rewrite /i/(.*) /index.html break;
Will work fine.
我觉得这很坑,我是真真的仔细看了nginx的文档,它所谓的current level, previous level,就算if内外,都不算是一个level。
另外不小心用了rewrite last,跳走了,同样会销毁我们辛勤培养的add_header。。。