reactjs - 将所有请求发送到 index.html 除了某些扩展

标签 reactjs nginx nginx-location nginx-config

我正在使用 nginx 来为我的 React 应用程序提供服务,它可以很好地将除静态文件之外的所有内容重定向到 index.html,其中包含以下内容:

location / {
  try_files $uri /index.html =404;
}

一段时间以来我对此很满意,但我注意到当某些图像和 javascript 文件在服务器上不可用时,会改为提供 index.html。这本身不是问题。

但是,当在应用程序之前添加缓存层时,它会缓存所有这些结果,因为它们确实有 200 作为状态代码。

我想要的是提供静态文件并将其他请求重定向到 index.html,当它们以某些扩展名(.js、.css、.png、.jpg、.gif 等)结尾时...)

例如

http://example.com/some/path -> /index.html
http://example.com/existing-file.doc -> /existing-file.doc
http://example.com/some/non-existing-image.png -> 404 error

因此像 http://example.com/main.1234.js 这样的地址如果存在就返回 js 文件,否则返回 404 响应,从不返回 index.html

我应该制作一个正则表达式 block ,例如:

location ~ \.js$|\.css$|\.png$|\.jpg$ {
    what do I write here?
}

我不完全确定如何最好地解决这个问题。

最佳答案

将 block 留空是完全有效的,它将继承周围 block 的 rootindex 的值。空位置 block 的默认操作类似于 try_files $uri $uri/=404;

您可能还想简化您的正则表达式,例如:

location ~ \.(js|css|png|jpg)$ { 
}

关于reactjs - 将所有请求发送到 index.html 除了某些扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57632225/

相关文章:

nginx - 在网站子目录中设置 phpMyAdmin

javascript - 为什么我们在 redux applyMiddleware 函数中执行 slice() 和 reverse() ?

css - 使用样式组件的媒体查询中的语法问题

javascript - ReactJS/通量: execute actions (ajax) in order

reactjs - 在不同容器中渲染组件并共享状态

Nginx 正在提供默认内容而不是我的内容

ruby-on-rails - rbenv : bundle: command not found on production server

php - Ubuntu WebServer 磁盘空间突然增加

nginx - 如何在 nginx 入口中将 header 传递给 auth-url

nginx - proxy_pass 基于 header 而不使用 if 条件