配置nginx实现跨域

项目中有时候会遇到跨域的问题,通常这个问题应该从server端解决,但是某些情况下我们不能修改server的代码,我们可以通过setup nginx来实现跨域。

还有一点需要注意,nginx不支持http 的option方法,所以需要做些特殊配置。下面是我项目中nginx.conf的详细配置(这个文件中没有配置nginx的负载均衡)同时nginx不支持else和其它的与 或 非 等操作:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  265;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    server {
        keepalive_requests 240;
        listen       80;   # nginx server deployed port (I am using docker, the docker port is 80)
        server_name  127.0.0.1; # nginx deployed server ip
        location  /{
       if ($request_method = OPTIONS ) {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'POST,GET,DELETE,OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'x-method-override,content-type,accept';
            proxy_pass  http://targetServerIP:port; # target server ip and port
            return 200;
         }
         if ($request_method != OPTIONS ){
             add_header 'Access-Control-Allow-Origin' '*';
             add_header 'Access-Control-Allow-Credentials' 'true';
             add_header 'Access-Control-Allow-Methods' 'POST,GET,DELETE,OPTIONS';
             add_header 'Access-Control-Allow-Headers' 'x-method-override,content-type,accept';
             proxy_pass  http://targetServerIP:port;  # target server ip and port
         }
        }
    }
}



你可能感兴趣的:(nginx)