nginx 解决跨域问题

使用 nginx 如何解决跨域问题,接口是已 .do 结尾的,如何通过 nginx 解决跨域

 server {
        listen       80;
        server_name  localhost;
        location ~* (\.do)$ {
            // 这里该怎么写呢?
        }
 }
阅读 3.7k
3 个回答
 server {
        listen       80;
        server_name  localhost;
        location ~* (\.do)$ {
           add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
            add_header Access-Control-Allow-Credentials 'true';
            add_header 'Access-Control-Allow-Headers' 'Accept, Authorization,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
            if ($request_method = 'OPTIONS') {
               add_header 'Access-Control-Allow-Origin' *;
               add_header 'Access-Control-Max-Age' 1728000;
               add_header 'Access-Control-Allow-Credentials' 'true';
               add_header 'Access-Control-Allow-Methods' 'GET, POST, DELETE, PUT, OPTIONS';
               add_header 'Access-Control-Allow-Headers' 'Accept, Authorization,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
               add_header 'Content-Type' 'text/plain charset=UTF-8';
               add_header 'Content-Length' 0;
               return 204;
           }
        }
 }
server {
    listen       80;
    server_name  localhost;
    location ~* (\.do)$ {
        proxy_set_header Host $host;
           add_header 'Access-Control-Allow-Origin' '*';
       add_header 'Access-Control-Allow-Credentials' 'true';
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
 }

跨域问题不应该在nginx解决,而且粗暴的添加set_header反而会出问题,nginx并不会对这些set_header进行验证,反而会出现一些容易造成浏览器混淆的问题。

跨域问题必须在后台解决,而后端框架一定能处理跨域问题。让开发改代码吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题