在不改变现有网站代码的前提下加入验证功能:
1.假设现有网站后端nodejs,端口3000,nginx配置如下
server { listen 80; server_name localhost; location /{ proxy_pass http://localhost:3000; } }
2.现在要为该网站添加验证功能,在不改变原有代码基础上需要做如下工作:
a.首先需要为nginx加入http_auth_request模块(附件),若nginx版本1.5.4+则无需添加该模块
b.新建node.js express网站,端口3001,并添加登录验证功能:
c.修改nginx配置文件如下:
server { listen 80; server_name localhost; location /{ auth_request /auth; proxy_pass http://localhost:3000; } location /auth{ proxy_pass http://localhost:3001; proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; } location /login{ proxy_pass http://localhost:3001; } error_page 403 /login; }
原理:访问80端口,先由auth_request将request送至/auth验证请求,如果是验证了的则返回200,nginx继续将请求发送至3000端口,如果/auth返回403,则nginx不会将请求发送至3000端口,最后定义一下403的位置即可。