Nginx 是一个高性能的 HTTP 和反向代理服务器,也用作邮件代理服务器。二级域名跨域是指在不同的二级域名之间进行跨域请求。由于浏览器的同源策略(Same-Origin Policy),默认情况下,不同源的网页之间不能进行交互。
Access-Control-Allow-Origin
头来允许特定的域名进行跨域请求。Access-Control-Allow-Methods
和 Access-Control-Allow-Headers
头来允许这些请求。原因:浏览器的同源策略限制了不同源的网页之间的交互。
server {
listen 80;
server_name example.com;
location /api {
proxy_pass http://backend.example.com;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header Access-Control-Expose-Headers 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
}
如果后端服务是使用 Node.js 和 Express 框架编写的,可以添加如下中间件:
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from server!' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
通过以上配置,可以有效解决 Nginx 二级域名跨域的问题。
领取专属 10元无门槛券
手把手带您无忧上云