惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
爱范儿
爱范儿
Martin Fowler
Martin Fowler
T
The Blog of Author Tim Ferriss
B
Blog RSS Feed
博客园 - 聂微东
G
GRAHAM CLULEY
Engineering at Meta
Engineering at Meta
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
WordPress大学
WordPress大学
Scott Helme
Scott Helme
AI
AI
S
Security Affairs
T
Threat Research - Cisco Blogs
M
MIT News - Artificial intelligence
T
Troy Hunt's Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
人人都是产品经理
人人都是产品经理
AWS News Blog
AWS News Blog
T
Threatpost
Cyberwarzone
Cyberwarzone
www.infosecurity-magazine.com
www.infosecurity-magazine.com
U
Unit 42
V
Vulnerabilities – Threatpost
J
Java Code Geeks
博客园 - Franky
月光博客
月光博客
Blog — PlanetScale
Blog — PlanetScale
NISL@THU
NISL@THU
D
Docker
小众软件
小众软件
N
News and Events Feed by Topic
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
A
Arctic Wolf
D
DataBreaches.Net
云风的 BLOG
云风的 BLOG
Forbes - Security
Forbes - Security
量子位
PCI Perspectives
PCI Perspectives
美团技术团队
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
I
InfoQ
Security Archives - TechRepublic
Security Archives - TechRepublic
有赞技术团队
有赞技术团队
腾讯CDC
P
Proofpoint News Feed
S
Security @ Cisco Blogs
G
Google Developers Blog
C
Cisco Blogs

博客园 - LungGiyo

frp 教程 001 局域网其他电脑也能访问wsl服务 001 nvm 管理不同版本的 node 与 npm 关于IP送中的影响和解决办法 Antigravity google ai 接入高德MCP 1.3.2 git使用ssh密钥 连接远程仓库 dynadot域名 托管到cloudflare , 使用cloudflare 的CDN功能 003 二进制日志-binlog Django 项目开发整体步骤(0 开始)+进阶 磊科N60Pro刷机 uni的页面解析 前端技术知识扫盲篇 使用 Lucky 为群晖 / 极空间 NAS 全服务启用 HTTPS 安全访问 00 docker 命令总结 001 Python 基础 麒麟系统升级openssh至openssh-10.0p1 零信任访问控制系统aTrust 蓝屏 Python PyInstaller 打包、Pyarmor加密等 001 安装wsl 2 && 开启 WSL2 Oxidized的model
nginx 跨域解决
LungGiyo · 2026-03-13 · via 博客园 - LungGiyo

本地调试,访问服务器api接口,跨域问题解决。

在serve里面最前面写:

set $cors_origin "";
# if ($http_origin = "http://localhost:7054") {
#     set $cors_origin $http_origin;
# }
# if ($http_origin = "https://xxxx.xxxx.com") {
#     set $cors_origin $http_origin;
# }
set $cors_origin $http_origin; #先改为不限制的,需要限制就注释这个,开启上面的
add_header 'Access-Control-Allow-Origin' $cors_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With, token, Origin, Accept, lang, Lang, Accept-Language, Cache-Control, Pragma' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Type, Authorization, token, Content-Disposition' always;
add_header 'Vary' 'Origin' always;

然后总入口:(对于把他就是在 伪静态这里, 对于其他的,就查看有无 【location / 】)

location ~* (runtime|application)/ {
    return 403;
}

location / {
    if ($request_method = OPTIONS) {
 
        add_header 'Access-Control-Allow-Origin' $cors_origin always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With, token, Origin, Accept, lang, Lang, Accept-Language, Cache-Control, Pragma' always;
        add_header 'Access-Control-Max-Age' 86400 always;
        add_header 'Content-Length' 0 always;
        add_header 'Content-Type' 'text/plain; charset=utf-8' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Type, Authorization, token, Content-Disposition' always;
        add_header 'Vary' 'Origin' always;       
        return 204;
    }

    add_header 'Access-Control-Allow-Origin' 'https://longjin.j8j0.com' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With, token, Origin, Accept' always;

    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.php?s=$1 last;
        break;
    }
}

附上测试demo:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>CORS 测试页</title>
    <style>
        body {
            margin: 0;
            padding: 16px;
            font-family: Arial, "Microsoft YaHei", sans-serif;
            background: #f5f5f5;
            color: #222;
        }

        .page-container {
            max-width: 900px;
            margin: 0 auto;
            background: #fff;
            border-radius: 8px;
            padding: 16px;
            box-sizing: border-box;
        }

        .page-title {
            margin: 0 0 12px;
            font-size: 22px;
        }

        .form-section {
            display: grid;
            gap: 12px;
        }

        .field-block {
            display: grid;
            gap: 6px;
        }

        .field-label {
            font-size: 14px;
            font-weight: 700;
        }

        .field-input,
        .field-select {
            width: 100%;
            min-height: 40px;
            padding: 10px 12px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 6px;
            font-size: 14px;
        }

        .action-row {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .action-button {
            min-width: 120px;
            min-height: 40px;
            padding: 0 16px;
            border: 0;
            border-radius: 6px;
            background: #1677ff;
            color: #fff;
            font-size: 14px;
            cursor: pointer;
        }

        .action-button.reset-button {
            background: #666;
        }

        .result-section {
            margin-top: 16px;
            display: grid;
            gap: 12px;
        }

        .result-card {
            background: #fafafa;
            border: 1px solid #e5e5e5;
            border-radius: 6px;
            padding: 12px;
        }

        .result-title {
            margin: 0 0 8px;
            font-size: 16px;
        }

        .result-pre {
            margin: 0;
            padding: 12px;
            background: #111;
            color: #0f0;
            border-radius: 6px;
            white-space: pre-wrap;
            word-break: break-all;
            overflow-x: auto;
            font-size: 12px;
            line-height: 1.6;
        }

        .tips-text {
            font-size: 13px;
            color: #666;
            line-height: 1.7;
        }

        @media (max-width: 320px) {
            .page-container {
                padding: 12px;
            }

            .action-button {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <main class="page-container">
        <h1 class="page-title">CORS 测试页</h1>

        <section class="form-section">
            <div class="field-block">
                <label class="field-label" for="requestUrl">请求地址</label>
                <input
                    id="requestUrl"
                    class="field-input"
                    type="text"
                    value="https://xxx.com/api/login/login?account=123&passwd=123"
                />
            </div>

            <div class="field-block">
                <label class="field-label" for="requestMethod">请求方式</label>
                <select id="requestMethod" class="field-select">
                    <option value="GET" selected>GET</option>
                    <option value="POST">POST</option>
                    <option value="OPTIONS">OPTIONS</option>
                </select>
            </div>

            <div class="field-block">
                <label class="field-label" for="requestBody">POST 请求体(JSON)</label>
                <textarea
                    id="requestBody"
                    class="field-input"
                    rows="6"
                >{"account":"234234234","passwd":"234234"}</textarea>
            </div>

            <div class="action-row">
                <button id="sendRequestButton" class="action-button" type="button">发送请求</button>
                <button id="clearResultButton" class="action-button reset-button" type="button">清空结果</button>
            </div>
        </section>

        <section class="result-section">
            <div class="result-card">
                <h2 class="result-title">执行结果</h2>
                <pre id="requestResult" class="result-pre">等待测试...</pre>
            </div>

            <div class="result-card">
                <h2 class="result-title">判断说明</h2>
                <div class="tips-text">
                    1. 如果浏览器控制台出现 <strong>CORS policy</strong>、<strong>blocked by CORS</strong>,就是跨域问题。<br />
                    2. 如果页面能拿到状态码和返回内容,通常说明浏览器没有被 CORS 拦截。<br />
                    3. 如果返回 404 / 500 / 302,那是接口或路由问题,不是 CORS 本身。<br />
                    4. 请同时打开浏览器开发者工具的 Console 和 Network 一起看。
                </div>
            </div>
        </section>
    </main>

    <script>
        (function () {
            const requestUrlInput = document.getElementById("requestUrl");
            const requestMethodSelect = document.getElementById("requestMethod");
            const requestBodyTextarea = document.getElementById("requestBody");
            const sendRequestButton = document.getElementById("sendRequestButton");
            const clearResultButton = document.getElementById("clearResultButton");
            const requestResultElement = document.getElementById("requestResult");

            function formatHeaders(headers) {
                const headerObject = {};
                headers.forEach(function (value, key) {
                    headerObject[key] = value;
                });
                return JSON.stringify(headerObject, null, 2);
            }

            function setResult(content) {
                requestResultElement.textContent = content;
            }

            async function sendRequest() {
                const requestUrl = requestUrlInput.value.trim();
                const requestMethod = requestMethodSelect.value;
                const requestBodyText = requestBodyTextarea.value.trim();

                if (!requestUrl) {
                    setResult("请求地址不能为空");
                    return;
                }

                const fetchOptions = {
                    method: requestMethod,
                    mode: "cors",
                    credentials: "include",
                    headers: {
                        "Accept": "application/json, text/plain, */*"
                    }
                };

                if (requestMethod === "POST") {
                    fetchOptions.headers["Content-Type"] = "application/json";
                    fetchOptions.body = requestBodyText || "{}";
                }

                if (requestMethod === "OPTIONS") {
                    fetchOptions.headers["Access-Control-Request-Method"] = "GET";
                    fetchOptions.headers["Access-Control-Request-Headers"] = "Content-Type, Authorization, X-Requested-With, token";
                }

                setResult("请求中...");

                try {
                    const response = await fetch(requestUrl, fetchOptions);
                    const responseText = await response.text();

                    const resultText =
                        "是否成功: " + response.ok + "\n" +
                        "状态码: " + response.status + " " + response.statusText + "\n\n" +
                        "响应头:\n" + formatHeaders(response.headers) + "\n\n" +
                        "响应正文:\n" + responseText;

                    setResult(resultText);
                } catch (error) {
                    setResult(
                        "请求失败。\n\n" +
                        "错误类型: " + (error && error.name ? error.name : "UnknownError") + "\n" +
                        "错误信息: " + (error && error.message ? error.message : String(error)) + "\n\n" +
                        "这类错误如果浏览器控制台同时出现 CORS policy / blocked by CORS,基本就是跨域被拦截。"
                    );
                    console.error("请求失败详情:", error);
                }
            }

            function clearResult() {
                setResult("等待测试...");
            }

            sendRequestButton.addEventListener("click", sendRequest);
            clearResultButton.addEventListener("click", clearResult);
        })();
    </script>
</body>
</html>