如何拦截Nginx多个特定Location,优先返回静态HTML再处理原请求?
拦截Nginx所有具体Location并前置HTML页面流程的解决方案
核心思路
通过全局统一配置替代每个业务Location中的重复try_files代码,利用Nginx的auth_request机制实现前置页面检查,同时排除无需拦截的路径(静态资源、提交接口),大幅提升配置可维护性。
具体配置示例
server { listen 80; server_name your-domain.com; recursive_error_pages on; # 全局启用两次验证:先SSO登录验证,再前置页面检查 auth_request /auth; auth_request /check-pre-pages; # 1. 排除静态资源:直接返回无需检查 location ~* \.(html|css|js|png|jpg)$ { auth_request off; root /path/to/your/static/files; } # 2. 排除用户提交接口:用户点击Next后的请求无需拦截 location = /api/ge/itc { auth_request off; limit_except POST { deny all; } proxy_set_header Host $host; proxy_pass <scheme>://<host>/api/internationalAgreement?redirecturi=$arg_ouri; error_page 379 =200 /userLocation?redirecturi=$upstream_http_x_mbe_redirect; } # 3. SSO登录验证的原有配置 location = /auth { # 你的SSO验证逻辑,比如调用内部认证接口 proxy_pass <scheme>://<auth-host>/validate; proxy_pass_request_body off; proxy_set_header Content-Length ""; } # 4. 前置页面检查的核心逻辑(内部调用) location = /check-pre-pages { internal; set $redirecturi $request_uri; proxy_method GET; proxy_set_header Host $host; proxy_pass <scheme>://<host>/api/internationalAgreement?redirecturi=$redirecturi; proxy_intercept_errors on; # 捕获后端自定义状态码 # 根据后端状态码跳转对应前置页面 error_page 378 =403 /internationalAgreement.html; error_page 395 =403 /supplier?redirecturi=$redirecturi; } # 5. 各个业务Location:无需添加try_files,全局已处理前置检查 location /workitem { proxy_set_header Host $host; proxy_pass <scheme>://<host>/workitem; } location = /search { proxy_set_header Host $host; proxy_pass <scheme>://<host>/search; } location ~ "^/content/([a-f\d]{24})/$" { proxy_set_header Host $host; proxy_pass <scheme>://<host>/content/$1; } # 6. 前置页面及后续跳转逻辑 location = /internationalAgreement.html { root /path/to/your/static/files; } location = /supplier { internal; set $redirecturi $arg_redirecturi; proxy_method GET; proxy_set_header Host $host; proxy_pass <scheme>://<host>/api/supplier?redirecturi=$redirecturi; proxy_intercept_errors on; # 可继续添加后续页面的error_page规则 error_page XXX =200 /userLocation?redirecturi=$redirecturi; } }
关键配置说明
- 全局
auth_request:在server级别配置两次验证,先完成SSO登录校验,再执行前置页面检查,避免在每个业务Location中重复配置。 auth_request off;:对静态资源、用户提交接口关闭验证,确保这些路径直接处理,不触发前置页面流程。proxy_intercept_errors on;:开启后Nginx会捕获后端返回的自定义状态码(如378、395),并通过error_page跳转到对应HTML页面。recursive_error_pages on;:允许递归处理多个前置页面的跳转(如协议页→位置页→供应商页),直到所有前置流程完成。
后端API调整说明
后端需要配合Nginx的auth_request逻辑调整状态码返回:
- 当用户需要展示前置页面时,返回非2xx状态码(如示例中的378、395),Nginx捕获后触发跳转。
- 当所有前置页面已完成时,返回2xx状态码,Nginx将继续处理原业务请求。
内容的提问来源于stack exchange,提问作者Harrison Waala
相关产品推荐
相关产品推荐

