Nginx CORS 配置指南
在 Web 开发中,跨源资源共享(CORS)是一个重要的概念。Nginx 作为一款高性能的 HTTP 和反向代理服务器,能够很好地处理 CORS 相关的问题。以下是一些关于如何在 Nginx 中配置 CORS 的指南。
基本配置
要启用 CORS,你需要在 Nginx 的 server 块中添加以下配置:
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
...
}
自定义域
如果你只想允许特定的域名访问,可以将 *
替换为具体的域名:
add_header 'Access-Control-Allow-Origin' 'https://example.com';
Options 预检请求
对于一些 HTTP 方法(如 OPTIONS
),浏览器会发送预检请求。Nginx 的配置需要允许这些预检请求:
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'https://example.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
return 204;
}
...
}
更多配置
Access-Control-Allow-Credentials
:控制是否允许携带凭证(如 cookies)。Access-Control-Expose-Headers
:允许客户端访问的响应头。
示例
server {
listen 80;
server_name localhost;
location / {
add_header 'Access-Control-Allow-Origin' 'https://example.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
...
}
location /api/ {
proxy_pass http://backend_server;
...
}
}
更多配置选项和详细信息,请访问 Nginx 官方文档。
Nginx Logo