You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中如何将静态HTML设置为网站首页(着陆页)

如何把静态HTML设为React项目的首页/着陆页

你要实现访问根域名时直接展示public文件夹里的静态HTML,有几种可行方案,根据你的需求选择:

方案1:服务器端配置(推荐,无需修改React代码)

不管是开发环境还是生产部署,直接让服务器在访问根路径/时返回landing.html:

  • 开发环境(Create React App):
    用react-app-rewired修改开发服务器配置,安装后在项目根目录创建config-overrides.js:

    module.exports = {
      devServer: function (configFunction) {
        return function (proxy, allowedHost) {
          const config = configFunction(proxy, allowedHost);
          // 根路径返回landing.html
          config.historyApiFallback.rewrites = [
            { from: /^\/$/, to: '/landing.html' }
          ];
          return config;
        };
      },
    };
    

    然后修改package.json的启动脚本为"start": "react-app-rewired start"。

  • 开发环境(Vite):
    修改vite.config.js,添加historyApiFallback配置:

    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [react()],
      server: {
        historyApiFallback: {
          rewrites: [
            { from: /^\/$/, to: '/landing.html' }
          ]
        }
      }
    });
    
  • 生产部署(比如Nginx):
    在Nginx配置文件里添加规则:

    server {
      listen 80;
      server_name xyzaa.com;
      root /path/to/your/react/build/folder;
    
      # 根路径返回landing.html
      location = / {
        try_files $uri /landing.html;
      }
    
      # 其他React路由路径交给index.html处理
      location / {
        try_files $uri $uri/ /index.html;
      }
    }
    

方案2:React路由内渲染静态HTML

如果需要React接管根路径,同时渲染静态HTML内容,可以创建一个组件加载landing.html:

  1. 确保已安装react-router-dom
  2. 修改路由配置(以React Router v6为例):
    import { Routes, Route } from 'react-router-dom';
    import LandingPage from './LandingPage';
    
    function App() {
      return (
        <Routes>
          <Route path="/" element={<LandingPage />} />
          {/* 你的其他路由 */}
        </Routes>
      );
    }
    
  3. 创建LandingPage.jsx组件:
    import { useEffect, useState } from 'react';
    
    function LandingPage() {
      const [htmlContent, setHtmlContent] = useState('');
    
      useEffect(() => {
        // 加载public里的landing.html
        fetch('/landing.html')
          .then(res => res.text())
          .then(html => setHtmlContent(html));
      }, []);
    
      // 注意:确保HTML内外部资源路径为相对路径,避免404
      return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
    }
    
    export default LandingPage;
    
    或者用iframe嵌入(更简单,但需调整样式适配):
    function LandingPage() {
      return <iframe src="/landing.html" frameBorder="0" style={{ width: '100%', height: '100vh', border: 'none' }} />;
    }
    

注意事项

  • 你之前使用的onEnter是React Router v5的写法,v6已废弃,v6中可通过组件内useEffect或Navigate组件替代。
  • 若采用方案1,确保landing.html内资源路径为相对路径(如./css/style.css),避免资源加载失败。

内容的提问来源于stack exchange,提问作者spiderweb191919

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 23:34:52