进一步配置Nginx支持HTML5 history state,React browser router

本文详细介绍了Nginx和Webpack Dev Server的历史回退(history fallback)配置方法,包括基本配置、优化配置及与index指令兼容的配置方式,确保在请求资源不存在时返回index.html,适用于SPA应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Nginx history fallback配置

基本(能用就行)

  # root /var/www/html;
  location / {
    # ...
    try_files $uri /index.html;
  }

更佳(仅在浏览器接受HTML时才尝试响应后备HTML)

  # root /var/www/html;
  location / {
    # ...
    set $fallback_uri /index.html;
    if ($http_accept !~ text/html) {
      set $fallback_uri $uri;
    }
    try_files $uri $fallback_uri =404;
  }

兼容(与指令indexautoindex并存)

  # root /var/www/html;
  location / {
    index index.html;
    autoindex on;
    # ...
    set $fallback_uri /index.html;
    if ($http_accept !~ text/html) {
      set $fallback_uri /null;
    }
    try_files $uri $uri/ $fallback_uri =404;
  }

WebpackDevServer history fallback配置

在webpack.config.js

基本

module.exports={
  //...
  devServer: {
    //...
    historyApiFallback: true,
  },
};

更佳

module.exports={
  //...
  devServer: {
    //...
    historyApiFallback: {
      htmlAcceptHeaders: ['text/html'], // 仅当浏览器接受HTML时,服务器才响应/index.html
    },
  },
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值