【发布时间】:2021-04-19 21:25:48
【问题描述】:
我正在使用 Nginx 为 MeiliSearch 设置反向代理。从源发送 POST 请求时,我收到 400: Origin is not allowed to make this request 错误。但是,如果请求没有来源,则一切正常。
有趣的是,响应还包括不同的标头,无论来源是否存在。
请求/响应
工作要求
| Header | Value |
|---|---|
| Content-Type | application/json |
| X-Meili-API-Key | asfasdfasdfasdfsafsdfasdfadsfsadff |
工作响应
| Header | Value |
|---|---|
| Server | nginx/1.18.0 |
| Date | Thu, 14 Jan 2021 19:49:02 GMT |
| Content-Type | application/json |
| Content-Length | 252 |
| Connection | keep-alive |
| Access-Control-Allow-Origin | * |
如您所见,Access-Control-Allow-Origin 应该是通配符。
请求失败
| Header | Value |
|---|---|
| Content-Type | application/json |
| X-Meili-API-Key | asfasdfasdfasdfsafsdfasdfadsfsadff |
| Origin | https://example.com |
响应失败
| Header | Value |
|---|---|
| Server | nginx/1.18.0 |
| Date | Thu, 14 Jan 2021 19:49:02 GMT |
| Content-Length | 252 |
| Connection | keep-alive |
Access-Control-Allow-Origin 现在不见了。
配置
这是完整的配置文件。
server {
server_name example.com;
location / {
if ($request_method ~* "(GET|POST)") {
add_header "Access-Control-Allow-Origin" *;
}
if ($request_method = OPTIONS ) {
add_header 'Access-Control-Max-Age' 1728000;
add_header "Access-Control-Allow-Origin" *;
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept, X-Meili-API-Key";
return 204;
}
proxy_pass http://127.0.0.1:7700;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 default_server;
listen [::]:80 default_server;
server_name example.com;
有什么想法吗?
【问题讨论】:
标签: nginx cors nginx-reverse-proxy nginx-config