Nginx和启用CORS

时间:2019-02-03 16:08:13

标签: nginx cors vagrant

NGINX配置未启用CORS

我整天都在搜索如何启用交叉请求,到目前为止我一无所获,我在127.0.0.1:3081/3080上提供了一个有角度的应用程序,我希望它向API发出CORS请求,当前正在运行nginx 1.11的无用虚拟机上运行。

server {
listen 80;
listen 443 ssl http2;
server_name harzreisen.test;
root "/home/vagrant/Code/harzreisen2/harzreisen-server/api";

index index.html index.htm index.php;

charset utf-8;

access_log off;
error_log  /var/log/nginx/harzreisen.test-error.log error;

sendfile off;

client_max_body_size 100m;

location / {

  dav_methods PUT DELETE MKCOL COPY MOVE;

  # Preflighted requestis
  if ($request_method = OPTIONS) {
    add_header "Access-Control-Allow-Origin" *;
    add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD, DELETE";
    add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    return 200;
  }

  # CORS WHITELIST EVERYTHING
  # This is allowing everything because I am running
  # locally so there should be no security issues.
  if ($request_method = (GET|POST|OPTIONS|HEAD|DELETE)) {
    add_header "Access-Control-Allow-Origin" *;
    add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
  }

   try_files $uri $uri/ /index.php$is_args$args;
}
}

只是网站没有达到POST请求,它给了我200个选项,仅此而已。有人可以向我解释一下发生了什么吗?

1 个答案:

答案 0 :(得分:0)

我建议在nginx.conf上使用more_set_headers而不是add_header;按照您的示例:

    more_set_headers "Access-Control-Allow-Origin" *;
    more_set_headers "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD, DELETE";
    more_set_headers "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    (...)

more_set_headers 指令是nginx的HttpHeadersMore中包含的nginx-extras flavor模块的一部分,您可以执行以下操作将其安装在ubuntu 16上:

  

sudo apt-get install nginx-extras