在踩坑之前,先来看一下location的语法规则
踩坑一:
当同一个server中,既存在动态请求代理,又存在静态资源请求代理,且静态资源请求代理为/ 全路径转发时,如何优先匹配动态请求
server { listen 8082; server_name 192.168.15.151; location ^~/file { proxy_pass http://192.168.2.151:9001/file; } location /{ root C:/nginx-1.18.0/nginx-1.18.0/hnevol_medical_wisdom_screen; try_files $uri $uri/ /index.html; } location /wisdomWs{ proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_pass http://192.168.2.151:12349/wisdomWs; } }
如果不在 /file 前 加^~ 请求还是转发到了/中,走了静态资源的代理
踩坑二:
当同一个server中,既存在动态请求代理,又存在静态资源请求代理,且动态请求代理为/ 全路径转发时, 如何优先匹配静态请求
server { listen 5001; server_name 127.0.0.1; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_buffering on; proxy_buffer_size 712k; proxy_buffers 2 712k; proxy_busy_buffers_size 712k; proxy_temp_path tempinx_proxy_temp 1 2; proxy_max_temp_file_size 20M; proxy_temp_file_write_size 712k; #location /wisdomApp/{ # proxy_pass http://127.0.0.1:8083/wisdomApp/; #} location /wisdomApp/{ try_files $uri $uri/ /wisdomApp/index.html; } location /wisdomWs{ proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_pass http://192.168.2.151:12349/wisdomWs; } location /file { proxy_pass http://192.168.2.151:9001/file; } location / { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; proxy_pass http://192.168.200.15:9000; } }
如上配置,在同一server中,既存在/的动态代理请求,又存在以/wisdomApp/为前缀的静态资源请求
按照以上配置,不做更改时,访问/wisdomApp/ 并没有访问到静态文件,而是提示未找到资源,并且按照之前的 在优先的匹配规则 /wisdomApp/ 前加上 ^~ 还是没有生效
解决方案
server { listen 8083; server_name 192.168.15.151; location /wisdomApp/{ try_files $uri $uri/ /wisdomApp/index.html; } }
额外添加一个内网server,内部代理为/全路径转发 静态资源,而原来的5001server中 将静态代理修改为动态请求,转发到8083的server中
发表评论