nginx if 语句在 location 中返回 404

Spy*_*dis 11 nginx cors

下面的块

location / {
    if ($http_origin ~* (https?://[^/]*\.example\.com(:[0-9]+)?)) {
        add_header 'Access-Control-Allow-Origin' "$http_origin";
    }
    try_files $uri $uri/ /index.php?$args;
}
Run Code Online (Sandbox Code Playgroud)

… 导致 404,因为上面的代码永远不会到达try_files指令,所以:

  1. 这与nginx的IfIsEvil有关吗?

  2. 如果是,那么是否有其他方法可以http_origin通过不使用 if 语句来测试?

我已经用 nginx > 1.4 (1.4.6, 1.7, 1.7.8) 试过了。

Ale*_*Ten 21

我会用map

map $http_origin $cors_header {
    default "";
    "~^https?://[^/]+\.example\.com(:[0-9]+)?$" "$http_origin";
}

server {
    ...
    location / {
        add_header Access-Control-Allow-Origin $cors_header;
        try_files $uri $uri/ /index.php;
    }
    ...
 }
Run Code Online (Sandbox Code Playgroud)

  • 使用多个具有不同变量的`map` (3认同)