我是 Nginx 新手,所以如果之前有人问过这个问题,请原谅我。我已经绞尽脑汁调试了好几个小时,却找不到与我的情况相关的信息。

我正在为一个网站项目运行一个远程 Ubuntu 服务器。我使用 Nginx 作为服务器。通过域名访问网站可以http://mywebsite.com正确地提供前端页面。我正在运行一个单独的本地程序,绑定到localhost:3000处理 API 请求,我想将请求重定向到该程序,链接为http://mywebsite.com/api/do_thing

使用基本 IP 地址和端口访问此端点可以正常工作,但使用域名则不起作用。Postman 每次都会返回 405 Not Allowed 响应。

经过一些研究,我尝试格式化我的mywebsite.com“默认”文件,如下所示:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/mywebsite.com;
    index index.html;
    server_name mywebsite.com www.mywebsite.com;
    location / {
        try_files $uri $uri/ /index.html;
    }

    location /api/do_thing {
        proxy_pass http://localhost:3000/do_thing;
        proxy_redirect http://mywebsite.com/api/do_thing http://0.0.0.0:3000/do_thing;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded_Proto $scheme;
    }
}

查看访问日志后,我发现http://mywebsite.com/api/do_thing从我的 IP 发送的 POST 请求甚至没有在 Nginx 中注册。我做错了什么,如何启用此类 API 请求转发?

1

  • 不,您不想重定向(这在 HTTP 中意味着非常不同的东西),您想重新路由或代理请求。“但不适用于使用域名” – 使用应用程序服务器的端口号?如果是这样,那么您真的应该先解决这个问题,然后再担心 nginx。


    – 

0