Nginx and SpringBoot Cross-Domain Configuration

nginx + springboot 跨域配置

对于Spring Boot和Nginx的跨域配置,我们需要在两个地方做出改变:Spring Boot应用和Nginx。

首先,让我们来看一下如何在Spring Boot中配置CORS(跨源资源共享)策略:

  1. 在Spring Boot中,你可以创建一个全局配置类,然后使用@CrossOrigin注解来实现跨域访问。比如:

    @Configuration
    public class MyConfiguration {
    
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**")
                            .allowedOrigins("*")
                            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                            .allowCredentials(true)
                            .maxAge(3600);
                }
            };
        }
    }
    

这个类会为所有的URL路径添加跨域配置,并允许任何来源访问。同时也支持几种主要的HTTP方法,如GET、POST、PUT、DELETE等。

然后在Nginx服务器上,你需要更新Nginx配置文件以允许CORS。以下是一个例子:

server {
    listen 80;
    server_name your_domain.com;

    location / {
        proxy_pass http://localhost:8080; # Spring Boot应用的地址
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # CORS headers
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization' always;

        # Preflight request. Reply successfully:
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
         }
    }
}

上面的Nginx配置将会接收到所有来自端口80的HTTP请求,并将其代理到本地的8080端口(你的Spring Boot应用服务器)。同时,它为所有的响应添加了CORS头部字段。

请注意,这些设置可能需要根据你的实际情况进行修改。