nginx如何修改ws请求的Access-Control-Allow-Origin为指定值
时间: 2024-05-23 20:08:19 浏览: 14
要修改WebSocket请求的Access-Control-Allow-Origin头,需要进行如下配置:
在nginx.conf中找到http段,添加以下代码:
```
map $http_origin $allow_origin {
default "";
"http://example.com" "http://example.com";
"https://example.com" "https://example.com";
"http://www.example.com" "http://www.example.com";
"https://www.example.com" "https://www.example.com";
}
server {
...
location / {
...
# 设置Access-Control-Allow-Origin头
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $allow_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' $allow_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
...
}
}
```
其中,map指令将允许的origin存储在$allow_origin变量中,server块中的location指令用于设置Access-Control-Allow-Origin头,当请求方法为OPTIONS时,设置Access-Control-Allow-*头并返回204状态码,当请求方法为POST时,设置Access-Control-Allow-*头。注意,这里设置的允许的origin可以是多个。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)