reactjs - 无法使用 url 导航通过 nginx 做出反应
问题描述
我正在使用 nginx(反应前端)提供我的静态文件。我为每个页面使用了不同的网址,例如 /login /user /home。
我的 nginx 不会将这些重定向到我的 index.html 文件。
我做了一些更改,现在我也无法获得我的主页。它返回无法获取 /。
这是我的 nginx.conf 文件。我在 Windows 上运行它。我的 index.html 在 build 文件夹中。如何让我的nginx在reactjs中使用Router和Link,这样我可以通过引用链接或者导航栏来获取页面?
worker_processes 5;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name ip;
location / {
root /Users/username/projectfolder/build;
index index.html index.htm;
try_files $uri $uri/ index.html;
proxy_pass http://ipaddress:portnumber;
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;
}
}
}
更新:
我尝试了以下配置
server {
listen some_port;
server_name some_ip;
root C:\\nginx-1.17.1\\build\\;
index index.html index.htm;
location /test/ {
alias C:\\nginx-1.17.1\\build\\;
index index.html index.htm;
try_files $uri \\index.html;
#internal;
#return index;
}
location = /index.html {
# no try_files here
return 502;
}
location / {
#root C:\\Users\\DEV-a0a02yc\\insurance_automation\\build;
try_files $uri $uri\ \index.html?$args;
#try_files $uri/ index.html;
proxy_pass http://some_ip:some_port;
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;
}
}
在 /test/ url 我得到一个空白页和一个重写/内部重定向错误说:
2019/07/01 09:53:22 [error] 17820#18008: *1 rewrite or internal redirection cycle while internally redirecting to "/favicon.ico\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html\ \index.html"
输入此 URL 时,如何在此处提供我的 index.html 文件以处理重定向?
解决方案
您的配置中的代理行是什么?
您不应该从 html 文件提供服务或代理传递到不同的地址吗?
我建议尝试从配置中删除代理行。
同样在不相关的注释中,proxy_pass 行无效。服务器地址“ipaddress”是一个很长的延伸(虽然不是不可能的 dns),端口“portnumber”肯定是无效的。
因此,所需的最低配置如下:
location / {
root /folder/subfolder/build;
try_files $uri /index.html;
}
root
定义你的 react 构建文件夹位置,并try_files
定义 nginx 应该查看请求的文件是否存在,如果不存在,它服务于index.html
.
推荐阅读
- java - 什么是用于执行 Azure Blob 加密/解密的默认加密策略
- javascript - 如何在“string.example”函数中使用变量
- ios - 如果我已经对该 Optional 执行了条件检查,有哪些避免强制展开的好方法?
- c++ - 无法从 main 引用 .cpp 和 .h 文件中的函数。C++
- windows - 在 windows bat 文件中,是否可以在同一行上运行多个命令,但不是循环的一部分?
- java - 满足过滤条件后如何从java流中抛出异常
- sql-server - 使用select语句将数据插入临时表?
- python - 如何使用 Python 中的变量修复文件重命名错误?
- c++ - 有像 QString(或 Java String)这样的 c++ 字符串库吗?
- chisel - 我如何才能为凿子中的零件提供黑盒代码?