我正在尝试将节点代理从端口移至端口8080
,80
但遇到了麻烦。我希望我的 RESTful API 位于 nginx 反向代理后面,该代理在本地监听端口 80 /api/path
。
(8080
由于防火墙过于严密,一些企业用户无法访问该端口。)
我过去常常将请求直接发送给https://domain.tld:8080/到http://本地主机:1337. 没有问题,通过:
server {
listen 8080;
server_name domain.tld;
ssl on; #some other SSL config removed for clarity
location / {
proxy_redirect off;
proxy_pass_header Server;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 5;
proxy_read_timeout 240;
proxy_intercept_errors on;
proxy_pass http://127.0.0.1:1337;
}
}
现在我正尝试通过以下方式将其移至api/path/
远离端口的位置8080
:
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name domain.tld;
root /path/to/html/;
ssl on; #some other SSL config removed for clarity
location /api/path/ {
proxy_redirect off;
proxy_pass_header Server;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 5;
proxy_read_timeout 240;
proxy_intercept_errors on;
proxy_pass http://127.0.0.1:1337;
}
}
其结果是:
$ curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{}' https://domain.tld/api/path
TTP/1.1 404 Not Found
Date: Thu, 08 Sep 2016 01:29:35 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 25
Connection: keep-alive
X-Powered-By: Express
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains;
Cannot POST /api/path
现在我读到你不能向静态页面发布信息,这意味着你要做类似的事情:
error_page 405 @405;
location = @405 {
root /path/to/html/;
}
但由于我找不到足够的信息,因此它无法正常工作。GET 可以正常工作,但 POST 会出错Cannot POST api/path
。我该怎么办?
感谢任何帮助。
更新
我需要启用proxy_redirect
@techraf 指出的,所以我的成功配置现在看起来像这样。希望它能帮助到别人。
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name domain.tld;
root /path/to/html/;
ssl on; #some other SSL config removed for clarity
location /api/path/ {
proxy_redirect http://localhost:1337/ /api/path/; #<-- change
proxy_pass_header Server;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 5;
proxy_read_timeout 240;
proxy_intercept_errors on;
proxy_pass http://127.0.0.1:1337;
}
}
答案1
如果您想指向/api/path/
重定向目的地的根目录,则需要使用:
proxy_redirect http://localhost:1337 https://domain.tld/api/path/