我目前正在使用Nginx作为反向代理和静态资源服务器。我一直在使用React Router的HashLocation设置,因为它是默认设置,可以使我在路由上刷新而无需任何额外的配置,并且没有任何问题,但是使用该设置的问题是需要在我的路由前面添加/#/(例如:http://example-app.com/#/signup)。
我现在正在尝试切换到React Router的HistoryLocation设置,但我无法弄清楚如何正确配置Nginx以为所有路由提供index.html(例如:http://example-app.com/signup)。
这是我的初始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;
}
}
使用HashLocation时,这个设置正常工作,但在改为HistoryLocation后(我所做的唯一更改),尝试刷新子路由URL时会返回404 Cannot GET。
if (!-e $request_filename){
rewrite ^(.*)$ /index.html break;
}
在location /
块中。这允许我刷新并直接访问路由作为顶级位置,但现在我不能提交PUT / POST请求,而是得到一个405方法不允许的错误。我可以看到请求没有被正确处理,因为我添加的配置现在将所有请求重写为/index.html,那里是我的API接收所有请求的地方,但我不知道如何同时实现能够将我的PUT / POST请求提交到正确的资源以及能够刷新和访问我的路由。