Nginx
如何設置結合 try_files 的 nginx 反向代理?
我想呼叫一個處理反向代理指令的命名位置。所以我在我的虛擬主機部分嘗試了以下幾行:
upstream node_upstream { server 127.0.0.1:8000; keepalive 64; } server { server_name my.host-name.com; listen 80; access_log /home/webhost/logs/my-host-name.access.log; error_log /home/webhost/logs/my-host-name.error.log; root /home/webhost/www/my.host-name.com/node-canary/public; location / { index index.html; try_files $uri $uri.html $uri/index.html $uri/ @node; } location @node { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://node_upstream/; proxy_redirect off; proxy_read_timeout 240s; } }
這很簡單,但是在執行它時,我得到了
nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /home/webhost/sites-enabled/my.host-name.com:29 nginx: configuration file /usr/local/etc/nginx/nginx.conf test failed
對我來說,這意味著我不能在*@node命名位置中使用代理傳遞。*
所以,我認為我可以通過簡單地將位於@node 位置的指令移動到根(即/)位置來超越 nginx。外面的一切都保持不變。像這樣:
server { server_name my.host-name.com; listen 80; access_log /home/webhost/logs/my-host-name.access.log; error_log /home/webhost/logs/my-host-name.error.log; root /home/webhost/www/my.host-name.com/node-canary/public; location / { index index.html; try_files $uri $uri.html $uri/index.html $uri/ $uri; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://node_upstream/; proxy_redirect off; proxy_read_timeout 240s; } }
但是通過這種設置,會發生一些奇怪的事情。當一個現有的靜態文件被命中時,代理連接(一個節點應用程序)正在響應請求——而不是通過靜態文件本身來響應。
這是請求返回有效響應的唯一情況。任何與靜態文件不匹配的路由都會返回 nginx 500 伺服器錯誤。
這讓我大吃一驚。
錯誤消息
"proxy_pass" cannot have URI part in ...
只是指/
您proxy_pass
聲明中的尾隨。利用:
proxy_pass http://node_upstream;
代替:
proxy_pass http://node_upstream/;
有關詳細資訊,請參閱此文件。