Подтвердить что ты не робот

Nginx Config для Cors - директива add_header запрещена

Я пытаюсь добавить директиву CORS в свой файл nginx для простого статического HTML-сайта. (взято отсюда http://enable-cors.org/server_nginx.html)

Будет ли причина, по которой он будет жаловаться на первую директиву add_header, указывающую, что директива 'add_header' здесь не разрешена '

Пример моего конфигурационного файла

server {
    if ($http_origin ~* (https?://[^/]*\.domain\.com(:[0-9]+)?)$) {
        set $cors "true";
    }

    if ($request_method = 'OPTIONS') {
        set $cors "${cors}options";
    }

    if ($request_method = 'GET') {
        set $cors "${cors}get";
    }
    if ($request_method = 'POST') {
        set $cors "${cors}post";
    }

    if ($cors = "trueget") {
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Credentials' 'true';
    }

    if ($cors = "truepost") {
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Credentials' 'true';
    }

    if ($cors = "trueoptions") {
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        return 204;
    }

    listen 8080;

    location / {
        root /var/www/vhosts/mysite;
    }
}
4b9b3361

Ответ 1

add_header должен быть помещен как в http, server, location, так и if in location.

Вы размещаете под if in server. Переместите их в блок location.

server {


    listen 8080;

    location / {
        root /var/www/vhosts/mysite;

        if ($http_origin ~* (https?://[^/]*\.domain\.com(:[0-9]+)?)$) {
            set $cors "true";
        }

        if ($request_method = 'OPTIONS') {
            set $cors "${cors}options";
        }

        if ($request_method = 'GET') {
            set $cors "${cors}get";
        }
        if ($request_method = 'POST') {
            set $cors "${cors}post";
        }

        if ($cors = "trueget") {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Credentials' 'true';
        }

        if ($cors = "truepost") {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Credentials' 'true';
        }

        if ($cors = "trueoptions") {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
            add_header 'Content-Length' 0;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            return 204;
        }
    }
}

Источник: http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header

Ответ 2

Правило if in location можно обойти некоторыми трюками, так что вам не нужно писать/включать правила CORS в каждом блоке location.

server {
    set $cors_origin "";
    set $cors_cred   "";
    set $cors_header "";
    set $cors_method "";

    if ($http_origin ~* "^http.*\.yourhost\.com$") {
            set $cors_origin $http_origin;
            set $cors_cred   true;
            set $cors_header $http_access_control_request_headers;
            set $cors_method $http_access_control_request_method;
    }

    add_header Access-Control-Allow-Origin      $cors_origin;
    add_header Access-Control-Allow-Credentials $cors_cred;
    add_header Access-Control-Allow-Headers     $cors_header;
    add_header Access-Control-Allow-Methods     $cors_method;
}

Это работает, потому что nginx не возвращает заголовок, если его значение является пустой строкой.

Ответ 3

Во-первых, позвольте мне сказать, что, оглянувшись по Сети, я нашел этот ответ повсюду:

location ~* \.(eot|ttf|woff|woff2)$ { add_header Access-Control-Allow-Origin *; }

Тем не менее, я решил ответить на этот вопрос отдельным ответом, так как мне удалось получить это конкретное решение, работая после того, как заработало еще десять часов, чтобы найти решение.

Похоже, что Nginx по умолчанию не определяет никаких [правильных] шрифтов MIME. Следуя этот tuorial, я обнаружил, что могу добавить следующее:

application/x-font-ttf           ttc ttf;
application/x-font-otf           otf;
application/font-woff            woff;
application/font-woff2           woff2;
application/vnd.ms-fontobject    eot;

В мой etc/nginx/mime.types файл.

Как указано, вышеприведенное решение затем работало. Очевидно, что этот ответ направлен на совместное использование шрифтов, но определенно стоит проверить, не определен ли тип MIME (правильно) для любого другого ресурса, с которым вы тоже боретесь.