ÔõÑùʹÓÃNginxʵÏÖ»ùÓÚÓû§½ÇÉ«µÄ»á¼û¿ØÖÆ
ÔõÑùʹÓÃnginxʵÏÖ»ùÓÚÓû§½ÇÉ«µÄ»á¼û¿ØÖÆ
СÐò£º
ÔÚÏÖ´úÍøÂçÓ¦ÓÃÖУ¬»á¼û¿ØÖÆÊÇÒ»¸öºÜÊÇÖ÷ÒªµÄÇå¾²ÐèÇó¡£Ðí¶àÓ¦ÓóÌÐòÐèÒª¶ÔÓû§µÄ»á¼û¾ÙÐнÇÉ«ÒÔ¼°È¨Ï޵ĿØÖÆ£¬ÒÔÈ·±£²î±ðÓû§Ö»ÄÜ»á¼ûËûÃǾ߱¸È¨ÏÞµÄÄÚÈÝ¡£NginxÊÇÒ»¸ö¸ßÐÔÄܵÄWebЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬²»µ«¿ÉÒÔ´¦Àí¾²Ì¬ÎļþЧÀÍ£¬»¹¿ÉÒÔͨ¹ýһЩÌØÕ÷ʵÏÖ»ù´¡µÄȨÏÞ¿ØÖÆ¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃnginxʵÏÖ»ùÓÚÓû§½ÇÉ«µÄ»á¼û¿ØÖÆ£¬²¢Ìṩ´úÂëʾÀý¡£
Ò»¡¢Nginx»ù±¾ÉèÖÃ
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚNginxµÄÉèÖÃÎļþÖÐÉèÖûù±¾ÐÅÏ¢ºÍ»á¼û¿ØÖƹæÔò¡£·¿ªNginxµÄÉèÖÃÎļþ£¨Ò»Ñùƽ³£ÊÇ/etc/nginx/nginx.conf£©£¬ÕÒµ½http¿é£¬ÔÚÆäÖÐÌí¼ÓÒÔÏÂÄÚÈÝ£º
http { ... # Óû§½ÇÉ«ÉèÖÃÎļþ·¾¶ include /etc/nginx/user_roles.conf; # ĬÈϾܾø»á¼û location / { deny all; } # ¾²Ì¬ÎļþЧÀÍ location /static/ { alias /path/to/static/files/; } # ¶¯Ì¬ÇëÇóÊðÀí location /dynamic/ { proxy_pass http://localhost:8000; # ÆäËûproxyÏà¹ØÉèÖà } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöÉèÖÃÖУ¬ÎÒÃÇÉèÖÃÁËĬÈϵľܾø»á¼û¹æÔò£¬²¢»®·ÖÉèÖÃÁ˾²Ì¬ÎļþЧÀͺͶ¯Ì¬ÇëÇóÊðÀí¡£½ÓÏÂÀ´£¬ÎÒÃǽ¨ÉèÒ»¸öרÃÅÓÃÓÚÓû§½ÇÉ«ÉèÖõÄÎļþuser_roles.conf£¬ÔÚ/etc/nginx/Ŀ¼Ï½¨Éè¸ÃÎļþ£¬²¢Ìí¼ÓÒÔÏÂÄÚÈÝ£º
user john: editor; user alice: admin;
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÉèÖÃÎļþÖУ¬ÎÒÃǽç˵ÁËÁ½¸öÓû§johnºÍalice£¬ÒÔ¼°ËûÃÇ»®·Ö¶ÔÓ¦µÄ½ÇÉ«¡£ÕâЩ½ÇÉ«½«ÓÃÓÚ»á¼û¿ØÖƵÄÅжϡ£
¶þ¡¢»ùÓÚÓû§½ÇÉ«µÄ»á¼û¿ØÖÆ
NginxÌṩÁËһЩ±äÁ¿ºÍÖ¸Á¿ÉÒÔÓÃÓÚƾ֤Óû§µÄ½ÇÉ«¾ÙÐлá¼û¿ØÖÆ¡£
ʹÓñäÁ¿¾ÙÐлá¼û¿ØÖÆ
NginxÌṩÁËÒ»¸ö$remote_user±äÁ¿£¬¸Ã±äÁ¿°üÀ¨ÁËÓû§µÄÓû§Ãû£¨Í¨¹ýHTTP»ù±¾ÈÏÖ¤»ñÈ¡£©¡£ÎÒÃÇ¿ÉÒÔͨ¹ýÅжϸñäÁ¿µÄÖµÀ´ÊµÏÖ»ùÓÚÓû§½ÇÉ«µÄ»á¼û¿ØÖÆ¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔʹÓÃifÖ¸ÁîʵÏÖÒÔϵĻá¼û¿ØÖƹæÔò£º
location /admin/ { if ($remote_user != "alice") { return 403; } # ÆäËûÉèÖÃÖ¸Áî }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýÖУ¬ÈôÊÇÓû§µÄÓû§Ãû²»ÊÇalice£¬Nginx½«·µ»Ø403¹ýʧҳÃ棬¾Ü¾ø»á¼û/admin/·¾¶ÏµÄÄÚÈÝ¡£
ʹÓÃLua¾ç±¾¾ÙÐлá¼û¿ØÖÆ
Nginx»¹Ö§³ÖǶÈëLua½ÅÔÀ´¾ÙÐиüÖØ´óµÄ»á¼û¿ØÖÆÅжϡ£ÎÒÃÇ¿ÉÒÔͨ¹ý±àдLua½ÅÔÀ´¶ÁÈ¡user_roles.confÎļþ£¬Æ¾Ö¤Óû§µÄ½ÇÉ«¾ÙÐлá¼û¿ØÖÆ¡£ÒÔÏÂÊÇÒ»¸öʾÀýµÄLua¾ç±¾£º
location /editor/ { access_by_lua_block { local roles_file = "/etc/nginx/user_roles.conf" local file = io.open(roles_file, "r") local roles = file:read("*a") file:close() local current_user = ngx.var.remote_user local role = string.match(roles, current_user .. ": (%a+);") if role ~= "editor" then ngx.exit(ngx.HTTP_FORBIDDEN) end } # ÆäËûÉèÖÃÖ¸Áî }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýÖУ¬ÎÒÃǶÁÈ¡ÁËuser_roles.confÎļþ£¬²¢Ê¹ÓÃÕýÔò±í´ïʽƥÅäÄ¿½ñÓû§µÄ½ÇÉ«¡£ÈôÊÇÄ¿½ñÓû§µÄ½ÇÉ«²»ÊÇeditor£¬Nginx½«·µ»Ø403¹ýʧҳÃ棬¾Ü¾ø»á¼û/editor/·¾¶ÏµÄÄÚÈÝ¡£
½áÂÛ£º
ͨ¹ýNginxµÄÉèÖúÍһЩÌØÕ÷£¬ÎÒÃÇ¿ÉÒÔʵÏÖ»ùÓÚÓû§½ÇÉ«µÄ»á¼û¿ØÖÆ¡£±¾ÎÄÌṩÁË»ù±¾µÄ´úÂëʾÀý£¬¹©¶ÁÕ߲ο¼ºÍʹÓá£ËäÈ»£¬ÕâÖ»ÊÇÒ»¸ö»ù´¡µÄʵÏÖÒªÁ죬ÏÖʵӦÓÃÖпÉÄÜ»¹ÐèҪ͎áÆäËûÇå¾²²½·¥£¬ÈçSSLÖ¤ÊéÒÔ¼°·À»ðǽµÈ£¬À´È·±£ÏµÍ³µÄÇå¾²ÐÔ¡£
²Î¿¼ÎÄÏ×£º
Nginx Documentation: https://nginx.org/en/docs/
OpenResty Lua Nginx Module Documentation: https://github.com/openresty/lua-nginx-module
ÒÔÉϾÍÊÇÔõÑùʹÓÃNginxʵÏÖ»ùÓÚÓû§½ÇÉ«µÄ»á¼û¿ØÖƵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡