×ðÁú¿­Ê±¹ÙÍøµÇ¼

nginx¿çÓòÔõô×ö

¿çÓòÇëÇóÎÊÌâ¿ÉÒÔͨ¹ýÔÚ nginx ÉèÖÃÖÐÐÞ¸ÄÏìӦͷÀ´½â¾ö£¬°üÀ¨ÔÊÐíËùÓÐÓò»á¼û¡¢Ìض¨Óò»á¼û¡¢Ìض¨ÒªÁìºÍ±êÍ·»á¼û¡¢Ð¯´øƾ֤»á¼û£¬ÒÔ¼°´¦ÀíÔ¤¼ìÇëÇó (options) ¡£Í¨¹ýÕâЩÉèÖ㬿çÓòÎÊÌ⽫»ñµÃ½â¾ö ¡£

nginx¿çÓò½â¾ö¼Æ»®

¿çÓòÎÊÌâ

¿çÓòÎÊÌâÊÇÖ¸ä¯ÀÀÆ÷³öÓÚÇ徲˼Á¿£¬ÏÞÖÆ´ÓÒ»¸öÓòµÄÍøÒ³Ö±½Ó»á¼ûÁíÒ»¸öÓòÖеÄ×ÊÔ´£¬´Ó¶øµ¼ÖÂAJAXÇëÇóʧ°Ü ¡£

nginx¿çÓò½â¾ö¼Æ»®

nginxͨ¹ýÐÞ¸ÄÏìӦͷÀ´½â¾ö¿çÓòÎÊÌ⣺

1. ÔÊÐíËùÓÐÓò»á¼û£¨²»Çå¾²£©

add_header Access-Control-Allow-Origin *;

µÇ¼ºó¸´ÖÆ

2. ÔÊÐíÌض¨Óò»á¼û

add_header Access-Control-Allow-Origin https://example.com;

µÇ¼ºó¸´ÖÆ

3. ÔÊÐíÌض¨ÒªÁìºÍ±êÍ·

add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE;
add_header Access-Control-Allow-Headers Content-Type, Authorization;

µÇ¼ºó¸´ÖÆ

4. ÔÊÐíЯ´øƾ֤£¨ÈçCookies£©

add_header Access-Control-Allow-Credentials true;

µÇ¼ºó¸´ÖÆ

5. Ô¤¼ìÇëÇó£¨OPTIONS£©

¹ØÓڷǼòÆÓÇëÇó£¨ÈçPOST£©£¬ä¯ÀÀÆ÷»á·¢ËÍOPTIONSÔ¤¼ìÇëÇóÀ´¼ì²éЧÀÍÆ÷ÊÇ·ñÔÊÐí¸ÃÇëÇó ¡£nginx¿ÉÒÔʹÓÃÒÔÏÂÉèÖÃÀ´ÏìÓ¦OPTIONSÇëÇó£º

location / {
    if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin https://example.com;
        add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE;
        add_header Access-Control-Allow-Headers Content-Type, Authorization;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Max-Age 3600;
        return 204;
    }
    # ÆäÓàÉèÖÃ...
}

µÇ¼ºó¸´ÖÆ

ÉèÖÃʾÀý

server {
    listen 80;
    server_name www.example.com;

    location / {
        add_header Access-Control-Allow-Origin https://example.com;
        add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE;
        add_header Access-Control-Allow-Headers Content-Type, Authorization;

        # ÆäÓàÉèÖÃ...
    }
}

µÇ¼ºó¸´ÖÆ

Íê³ÉÉÏÊöÉèÖú󣬿çÓòÎÊÌ⽫»ñµÃ½â¾ö ¡£

ÒÔÉϾÍÊÇnginx¿çÓòÔõô×öµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±¹ÙÍøµÇ¼ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼ ¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼ʵʱÐÞÕý»òɾ³ý ¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
ÍøÕ¾µØͼ