我无法弄清楚如何让nginx通过React Router的HistoryLocation配置来提供我的静态文件。我尝试过的设置会阻止我刷新或访问网址作为顶级位置(使用404无法获取/ ...)或阻止我提交POST请求。
这是我最初的nginx设置(不包括我的mime.types文件):
nginx.conf
# The maximum number of connections for Nginx is calculated by:
# max_clients = worker_processes * worker_connections
worker_processes auto;
# Process needs to run in foreground within container
daemon off;
events {
worker_connections 1024;
}
http {
# Hide nginx version information.
server_tokens off;
# Define the MIME types for files.
include /etc/nginx/mime.types;
# Update charset_types due to updated mime.types
charset_types
text/xml
text/plain
text/vnd.wap.wml
application/x-javascript
application/rss+xml
text/css
application/javascript
application/json;
# Speed up file transfers by using sendfile() to copy directly
# between descriptors rather than using read()/write().
sendfile on;
# Define upstream servers
upstream node-app {
ip_hash;
server 192.168.59.103:8000;
}
include sites-enabled/*;
}
默认
server {
listen 80;
root /var/www/dist;
index index.html index.htm;
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 1d;
}
location @proxy {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
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 X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_redirect off;
proxy_pass http://node-app;
proxy_cache_bypass $http_upgrade;
}
location / {
try_files $uri $uri/ @proxy;
}
}
我期待nginx作为反向代理的所有功能都在那里,除了它给我前面提到的404 Can not GET。在寻找解决方案之后,我尝试添加
if (!-e $request_filename){
rewrite ^(.*)$ /index.html break;
}
location /
块中的。这允许我刷新并直接访问路由作为顶部位置,但现在我无法提交PUT / POST请求,而是不允许返回405方法。我可以看到请求没有得到正确处理,因为我添加的配置现在将我的所有请求重写为/index.html,以及我的API接收所有请求的地方,但我不知道如何完成能够将我的PUT / POST请求提交给正确的资源,以及能够使用React Router的HistoryLocation刷新和访问我的路由。