Nginx 跨域配置

背景

最近有在开发的一个前后端分离系统,在做 Nginx 的相关跨域配置时,遇到了比较奇怪的问题。当前端发起的请求,经后端处理后,返回的状态码是 4XX 或者 5XX 时,跨域的资源无法正常返回,即使配置上了 add_header

原因和解决方式

Nginx 官方文档 中有说到,只有当响应状态码为以下几种类型中之一时,add_header 才会生效。为了让 add_header 在所有情况下都生效,可以在后面加上 always 参数,即可解决。

Adds the specified field to a response header provided that the response code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). The value can contain variables.

There could be several add_header directives. These directives are inherited from the previous level if and only if there are no add_header directives defined on the current level.

If the always parameter is specified (1.7.5), the header field will be added regardless of the response code.

参考配置

给一个我的 Laravel 项目的配置,仅供参考。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server {
listen 80;
server_name domain;
root /var/www/html/site/public;

add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Methods * always;

location / {
try_files $uri $uri/ /index.php?$query_string;
}

location ~ .php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi.conf;
}

}