如何配置Nginx proxy_pass以正常加载含CDN静态资源的外部网站?
问题描述
我用Elementor搭建了一个外部落地页,地址为https://new.domain.com/landing。通过Nginx的proxy_pass将其代理到自定义路径/custom/newpage后,部分静态资源(如.js文件)无法加载,页面无法正常运行。我尝试过的Nginx配置如下:
location /custom/newpage { proxy_pass https://new.domain.com/landing; proxy_set_header Host new.domain.com; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Accept-Encoding ""; proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2; proxy_ssl_session_reuse off; proxy_ssl_server_name on; }
解决方案及配置说明
问题核心是路径映射不匹配:Elementor生成的页面中,静态资源的路径可能以源站的/landing为基准,代理后浏览器会错误地以/custom/newpage的上级路径去请求资源,导致404;同时部分资源可能直接引用了源站域名,需要替换为代理路径。
以下是修复后的完整Nginx配置:
location /custom/newpage { # 末尾添加/,确保路径正确转发:/custom/newpage/xxx → https://new.domain.com/landing/xxx proxy_pass https://new.domain.com/landing/; proxy_set_header Host new.domain.com; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # 关闭压缩,确保sub_filter能正常处理响应内容 proxy_set_header Accept-Encoding ""; proxy_ssl_protocols TLSv1.2 TLSv1.3; proxy_ssl_session_reuse off; proxy_ssl_server_name on; # 替换页面中的base标签,让所有相对路径以代理路径为基准 sub_filter '<base href="https://new.domain.com/landing/"' '<base href="/custom/newpage/">'; # 替换页面中直接引用源站路径的资源链接 sub_filter 'https://new.domain.com/landing/' '/custom/newpage/'; sub_filter_once off; sub_filter_types text/html application/javascript text/css; }
关键配置解释
proxy_pass https://new.domain.com/landing/:末尾的斜杠是关键,Nginx会将/custom/newpage之后的路径部分追加到/landing/后,保证资源请求能正确转发到源站对应路径。sub_filter系列配置:批量替换页面中所有指向源站的资源路径,改为代理后的自定义路径,确保浏览器从正确的URL加载资源。sub_filter_once off表示替换所有匹配项,sub_filter_types指定需要处理的响应类型。- 升级
proxy_ssl_protocols到TLSv1.2和TLSv1.3,适配Cloudflare的SSL要求,提升安全性和兼容性。
内容的提问来源于stack exchange,提问作者Pavel Klyuev
相关产品推荐
相关产品推荐

