Nginx 是一个高性能的 Web 服务器和反向代理服务器,可以在生产环境中实现跨域请求
Nginx 配置代码及注释
server {
listen 80; # 监听端口号为80
server_name example.com; # 监听的域名
location /api {
# 后端接口地址,这里需要替换为你的后端接口地址
proxy_pass http://127.0.0.1:8080;
# 允许跨域请求的域名和请求头,这里需要替换为你实际的域名和请求头
add_header 'Access-Control-Allow-Origin' 'http://localhost:3000';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Content-Type,Authorization';
# 处理 OPTIONS 请求
if ($request_method = 'OPTIONS') {
# 允许跨域请求的 HTTP 方法
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
# 预检请求的超时时间
add_header 'Access-Control-Max-Age' 1728000;
# 预检请求的响应头信息
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
# 返回状态码 204,表示请求成功但不返回任何内容
return 204;
}
}
}
这段代码实现了在 Nginx 中添加跨域请求的配置。下面是代码的详细注释:
listen 80
; 指定监听的端口号为80
,也可以替换为其他端口号。server_name
example.com
; 指定监听的域名,需要替换为你实际的域名。location /api
{ 指定匹配的 URL 路径,需要根据实际情况进行替换。proxy_pass
http://127.0.0.1:8080
; 指定后端接口地址,需要替换为你实际的后端接口地址。- add_header ‘
Access-Control-Allow-Origin
’ ‘http://localhost:300
0’;允许跨域请求的域名,需要替换为你实际的域名。 add_header
‘Access-Control-Allow-Credentials
’ ‘true
’; 允许发送Cookie
,需要根据实际情况进行修改。add_header
‘Access-Control-Allow-Headers
’
‘Content-Type,Authorization
’; 允许发送的请求头,需要根据实际情况进行修改。- if ($request_method = ‘OPTIONS’) { 处理 OPTIONS
请求,这是一种预检请求,用于检查服务器是否允许实际的跨域请求。需要根据实际情况进行修改。 add_header
‘Access-Control-Allow-Methods
’ ‘GET, POST, OPTIONS, PUT,DELETE’; 允许的跨域请求的 HTTP 方法,需要根据实际情况进行修改。add_header
‘Access-Control-Max-Age
’ 1728000; 预检请求的超时时间,单位为秒。这里设置为
20 天,需要根据实际情况进行修改。add_header
'Content-Type' 'text/plain
;charset=utf-8
’;预检请求的响应头信息,需要根据实际情况进行修改。add_header
‘Content-Length
’ 0; 预检请求的响应头信息,需要根据实际情况进行修改。- return 204; 返回状态码 204,表示请求成功但不返回任何内容。
上述配置可以放置在 Nginx 的配置文件中,保存并重启 Nginx 后生效。这样就可以实现在生产环境中通过 Nginx 配置跨域请求。