How to properly setup nginx Access-Control-Allow-Origin into response header based on the Origin header from the request?

前端 未结 2 1157
-上瘾入骨i
-上瘾入骨i 2020-12-05 02:46

I am looking for a nginx config setup that does setup the Access-Control-Allow-Origin to the value received in the Origin.

It seems that th

2条回答
  •  盖世英雄少女心
    2020-12-05 03:46

    Using if can sometimes break other config such as try_files. You can end up with unexpected 404s.

    Use map instead

    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;
        }
        ...
     }
    

    If is evil

提交回复
热议问题