nginxÔõÑù½â¾ö¿çÓòÎÊÌâ
ÔõÑù½â¾ö¿çÓòÎÊÌ⣿ͨ¹ýÉèÖà nginx ÖÐµÄ cors Í·¡£cors ±ê×¼ÔÊÐí²î±ðÔ´Ö®¼ä¹²Ïí×ÊÔ´£¬°üÀ¨£ºÔÊÐí¿çÓòÇëÇóµÄÓò£ºaccess-control-allow-originÔÊÐí¿çÓòÇëÇóµÄÒªÁ죺access-control-allow-methodsÔÊÐí¿çÓòÇëÇóµÄÍ·×ֶΣºaccess-control-allow-headersÔÊÐíЯ´øƾ֤£ºaccess-control-allow-credentialsÔ¤¼ìÇëÇóÓÐÓÃÆÚ£ºaccess-control-max-age
ÔõÑùʹÓà nginx ½â¾ö¿çÓòÎÊÌâ
¿çÓòÊÇÒ»ÖÖä¯ÀÀÆ÷Çå¾²»úÖÆ£¬µ± Web Ó¦ÓóÌÐò´ÓÓëÆä×ÔÉíÔ´Óò²î±ðµÄÓòÇëÇó×ÊԴʱ£¬¾Í»á±¬·¢¿çÓòÎÊÌ⡣ĬÈÏÇéÐÎÏ£¬ä¯ÀÀÆ÷»á×èÖ¹¿çÓòÇëÇóÒÔ±£»¤Óû§ÃâÊÜ¿çÕ¾µã¾ç±¾¹¥»÷µÈ¶ñÒâÔ˶¯µÄÓ°Ïì¡£
CORS£º½â¾ö¿çÓòÎÊÌâµÄ±ê×¼
½â¾ö¿çÓòÎÊÌâµÄ±ê×¼ÒªÁìÊÇʹÓÿçÓò×ÊÔ´¹²Ïí (CORS)¡£CORS ÊÇÒ»×é HTTP Í·£¬ÔÊÐíÔÚ²î±ðÔ´Ö®¼ä¹²Ïí×ÊÔ´¡£
ʹÓà nginx ÉèÖà CORS
¿ÉÒÔʹÓà nginx ÖÐµÄ add_header Ö¸ÁîÉèÖà CORS£º
server { # ... # ÔÊÐí¿çÓòÇëÇó add_header 'Access-Control-Allow-Origin' '*'; # ÔÊÐí¿çÓòÇëÇóµÄÒªÁì add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; # ÔÊÐí¿çÓòÇëÇóµÄÍ·×ֶΠadd_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization'; # ÔÊÐíÔÚÔ¤¼ìÇëÇóÖÐЯ´øƾ֤£¨ÀýÈ磬cookie£© add_header 'Access-Control-Allow-Credentials' 'true'; # Ô¤¼ìÇëÇóµÄÓÐÓÃÆÚ£¨ÒÔÃëΪµ¥Î»£© add_header 'Access-Control-Max-Age' '3600'; # ... }
µÇ¼ºó¸´ÖÆ
ÉèÖÃÏêÇ飺
Access-Control-Allow-Origin: Ö¸¶¨ÔÊÐí¿çÓòÇëÇóµÄÓò¡£* ÌåÏÖÔÊÐíËùÓÐÓò¡£
Access-Control-Allow-Methods: Ö¸¶¨ÔÊÐí¿çÓòÇëÇóµÄÒªÁì¡£
Access-Control-Allow-Headers: Ö¸¶¨ÔÊÐí¿çÓòÇëÇóµÄÍ·×ֶΡ£
Access-Control-Allow-Credentials: Ö¸¶¨ÊÇ·ñÔÊÐí¿çÓòÇëÇóЯ´øƾ֤¡£
Access-Control-Max-Age: Ö¸¶¨Ô¤¼ìÇëÇóµÄÓÐÓÃÆÚ¡£
HTTP Ô¤¼ìÇëÇó
¹ØÓÚijЩÇëÇó£¨ÀýÈ磬´øÓÐ×Ô½ç˵ HTTP Í·×ֶλòʹÓ÷ǼòÆÓÒªÁìµÄÇëÇ󣩣¬ä¯ÀÀÆ÷»áÏÈ·¢ËÍÒ»¸öÔ¤¼ìÇëÇóÀ´¼ì²éЧÀÍÆ÷ÊÇ·ñÔÊÐí¸Ã¿çÓòÇëÇó¡£ÈôÊÇЧÀÍÆ÷ÏìÓ¦µÄÔ¤¼ìÇëÇó°üÀ¨Êʵ±µÄ CORS Í·£¬ä¯ÀÀÆ÷½«ÔÊÐíÏÖʵµÄ¿çÓòÇëÇó¡£
ͨ¹ýÉèÖà nginx µÄ CORS Í·£¬¿ÉÒÔÔÊÐí¿çÓòÇëÇó²¢½â¾ö¿çÓòÎÊÌ⣬ȷ±£ Web Ó¦ÓóÌÐò¿ÉÒÔÔÚ²î±ðÔ´Ö®¼äͨѶ¡£
ÒÔÉϾÍÊÇnginxÔõÑù½â¾ö¿çÓòÎÊÌâµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡