## Nginx如何解决跨域问题 ### 问题简述: docker启动的nginx,修改配置文件default.conf,允许跨域不生效。 平台:MacOS M1pro ### 问题描述: 我使用Vue实现了一个前端项目,使用Nginx静态资源代理监听80端口,向本地后端服务[http://localhost:9000/](https://link.segmentfault.com/?enc=Odimf7RAe5AHbdEjjFqkfA%3D%3D.Ba3Gq2I9usenkw8dS34%2F1ZSZNASGm%2Fqg2FU936%2FdsSY%3D)发送Get请求 // 跨域访问后端项目 axios.get("http://localhost:9000/hello") .then(function (response) { console.log(response) }) go语言实现的后端项目核心代码,启动服务监听9000端口 func handler(w http.ResponseWriter, r *http.Request) { _, err := fmt.Fprintf(w, "Hello, 第一条消息") if err != nil { return } } func main() { http.HandleFunc("/hello", handler) err1 := http.ListenAndServe(":9000", nil) if err1 != nil { return } } * * * 将Vue项目打包为dist,复制到docker容器的`/usr/share/nginx/html`目录中,配置文件为: server { listen 80; listen [::]:80; server_name localhost; #access_log /var/log/nginx/host.access.log main; location / { #允许跨域请求的域,* 代表所有 add_header 'Access-Control-Allow-Origin' *; root /usr/share/nginx/html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } 启动过程略过,可以发现跨域错误  直接使用浏览器访问9000端口是正常的:  如何在Nginx解决跨域问题,我已经了解前端虚拟代理、后端允许跨域方法。 本问题只讨论nginx如何允许跨域。 已经尝试的方法如下,已确定修改配置文件后重启nginx。 方法一: #access_log /var/log/nginx/host.access.log main; location / { root /usr/share/nginx/html; index index.html index.htm; #允许跨域请求的域,* 代表所有 add_header 'Access-Control-Allow-Origin' *; } 方法二: location / { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Credentials' 'true'; if ( $request_method = 'OPTIONS' ) { return 200; } root /usr/share/nginx/html; index index.html index.htm; } 方法三:增加always location / { add_header Access-Control-Allow-Origin * always; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Credentials' 'true' always; if ( $request_method = 'OPTIONS' ) { return 200; } root /usr/share/nginx/html; index index.html index.htm; } 网络上可以直接搜索到的方法基本都尝试过,求大佬解答,并进一步讨论相关理论(从Nginx实现方法角度) 特别强调,本项目使用Docker启动容器,因此容器向localhost分发流量的域名为host.docker.internal