Files
nginxserver/scripts/enable_cors.sh
2026-07-16 13:03:11 +08:00

24 lines
1.1 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
# 启用 CORS 跨域支持
# 步骤1: 恢复带 CORS headers 的 nginx.conf
cp /etc/nginx/nginx.conf.bak.cors /etc/nginx/nginx.conf
# 步骤2: 给静态资源 location 也加 CORS
# (因为 add_header Cache-Control 会覆盖 http 块继承的 CORS headers
for f in /etc/nginx/conf.d/*.conf; do
if ! grep -q 'Access-Control-Allow-Origin' "$f"; then
sed -i 's/add_header Cache-Control/add_header Access-Control-Allow-Origin * always;\n add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;\n add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;\n add_header Cache-Control/' "$f"
fi
done
# 步骤3: 验证并重载
echo "=== nginx -t ==="
nginx -t && systemctl reload nginx && echo "=== DONE ==="
# 步骤4: 验证 CORS 是否生效
echo ""
echo "=== 验证 CORS ==="
curl -sI -H "Origin: http://test.com" -k https://gw.server.zgitm.com/ 2>&1 | grep -i access-control
curl -sI -H "Origin: http://test.com" -k https://web.gw.zgitm.com/ 2>&1 | grep -i access-control
echo "=== 完成 ==="