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¿çÓòÔõô×öµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡