如何解决nginx 中的多个位置不起作用 - 错误 404
我正在尝试运行两个 nodejs 应用程序,一个在默认路径 (/) 上,另一个在 /api 上,我尝试了多种方法,但多个位置无法使用nginx ,只有根域 (/) 工作正常,我分配哪个应用程序(第二个或第一个)都没有关系。如果我尝试访问 (/api) 它返回 404 not found 并且 (/) 路径工作正常。 这是我的默认 nginx 文件
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name example.com;
location /api {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
try_files $uri $uri/ =404;
}
location / {
proxy_pass http://localhost:8081;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
try_files $uri $uri/ =404;
}
}
我做错了什么。任何帮助都将得到回报。谢谢
解决方法
在做了很多谷歌搜索并尝试了很多方法后,我找到了解决方案,而不是使用 react app 作为动态加载,我生成了一个 react 构建并将其存储在特定位置,并在主要位置提供这些构建文件nginx。
location / {
root /home/user/gui/build;
try_files $uri /index.html;
}
location /api/ {
proxy_pass http://localhost:3002/;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location /static/ {
root /home/user/gui;
try_files
/gui/build$uri
=404;
}
所以这里 (/) 将尝试 root 文件夹中的文件 (/home/user/gui/build) 和我们有由 react build 生成的 index.html,这个 index.html 将被提供。现在下一个问题是提供反应生成的静态文件,所以我创建了一个单独的位置 (/static/) 与 / 路径相同的逻辑。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。