宝塔Nginx跨域配置教程
在宝塔面板中配置 Nginx 跨域(CORS)的步骤如下:
方法一:通过宝塔面板界面配置
1.登录宝塔面板
打开宝塔面板,进入「网站」模块。
2.找到目标网站
点击需要配置跨域的网站右侧的「设置」按钮。
3.修改配置文件
进入「配置文件」标签页,在 server 或 location 块中添加以下跨域配置:
# 允许跨域请求
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
# 处理 OPTIONS 预检请求
if ($request_method = 'OPTIONS') {
return 204;
}
- 允许所有域名跨域:使用 Access-Control-Allow-Origin *
- 允许特定域名:替换 * 为域名,例如 https://example.com
4.保存并重启Nginx
点击「保存」,然后重启 Nginx 服务。
方法二:直接修改 Nginx 配置文件
1.定位配置文件
配置文件通常位于
/www/server/panel/vhost/nginx/你的网站域名.conf。
2.编辑配置文件
在 server 或 location 块中添加跨域配置(同上)。
3.检查语法并重启
nginx -t # 检查配置语法
systemctl restart nginx # 重启 Nginx
高级配置示例
server {
listen 80;
server_name example.com;
location / {
# 基础跨域配置
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'Content-Type, Authorization';
add_header Access-Control-Allow-Credentials true;
# 处理 OPTIONS 预检请求
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'Content-Type, Authorization';
add_header Access-Control-Max-Age 1728000;
add_header Content-Type 'text/plain; charset=utf-8';
add_header Content-Length 0;
return 204;
}
# 其他配置...
}
}
注意事项
安全性
- 生产环境建议明确指定允许的域名(如 Access-Control-Allow-Origin https://example.com),避免使用 *。
- 如需携带 Cookie,需设置 Access-Control-Allow-Credentials true,且 Access-Control-Allow-Origin 不能为 *。
缓存优化
通过 Access-Control-Max-Age 减少预检请求次数。
调试工具
使用浏览器开发者工具(Network 标签)检查响应头是否生效。
通过以上配置,Nginx 即可支持跨域请求。如果遇到问题,可通过 nginx -t 检查语法或查看错误日志(/www/wwwlogs/error.log)。