63 Nginx解决跨域问题的具体实现

63 Nginx解决跨域问题的具体实现

63.1 add_header

语法 add_header name value
默认值 -
位置 http 、server 、location

 

 

 

 

添加头信息:add_header Access-Control-Allow-Origin 、add_header Access-Control-Allow-Methods

Access-Control-Allow-Origin:允许跨域访问的源地址信息,可配置多个(逗号分隔),也可以使用 * 代表所有源

Access-Control-Allow-Methods:允许跨域访问的请求方式,GET、POST、PUT、DELETE......,可配置多个(逗号分隔)

63.2 增加配置

[root@nginx-100 /usr/local/nginx/conf]# cat nginx.conf
user www;
worker_processes 2;
error_log logs/error.log;
pid logs/nginx.pid;
#daemon on; # 默认on
events {
    accept_mutex on;
    multi_accept on;
    worker_connections  1024;
    use epoll;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout  65;
    include nginx_gzip.conf;

    # 模拟服务器a
    server {
        listen       80;
        server_name  localhost;
                
        location / {
          root html;
          index index.html index.htm;
        }
    }  
   # 模拟服务器b
    server {
        listen       8080;
        server_name  localhost;

        location /getUser {
           add_header Access-Control-Allow-Origin http://10.0.0.100;
       add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;
           default_type application/json;
           return 200 '{"id":1,"name":"TOM","age":18}';
        }

        error_page   500 502 503 504 404 /50x.html;
        location = /50x.html {
            root   html;
        }
    }  
}
[root@nginx-100 /usr/local/nginx/conf]# nginx -t && nginx -s reload
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

63.3 演示

 浏览器访问:http://10.0.0.100/a.html

image

 

———————————————————————————————————————————————————————————————————————————

                                                                                                                         无敌小马爱学习

posted on 2026-05-19 00:24  马俊南  阅读(13)  评论(0)    收藏  举报