react部署到服务器上,现在需要部署到服务器的子目录中,该怎么做?

项目部署,服务器上有很多项目,所以现在需要部署到子目录中
例如:www.xxxx.com/demo/
当输入以上网址时加载我的项目,这就需要在服务器里边建一个demo的文件夹,并将我的react打包之后的代码放进去。
现在出现的问题是当输入网址的时候www.xxxx.com/demo/index.html 加载的是www.xxxx.com#/
这里我用的是HashRouter
请问有没有办法前端设置什么实现以上
就是输入www.xxxx.com/demo/index.html然后加载的是www.xxxx.com/demo/index.html/#/
路由配置:

<HashRouter history={hashHistory} basename="/demo/index.html">
    <Switch>
        <Route path="/" component={Login} />
        <Redirect from="/login" to="/"/>
        <Route path="/" component={Base} />
    </Switch>
    {/*<Route path="*" component={NotFound}/>*/}
</HashRouter>,

其中basename试过“/Demo” 还有“/Demo/”结果都是一样的都是跳转回www.xxxx.com/#/

阅读 11.4k
3 个回答

谢邀!
单页面部署到服务器
单页面应用应该放到nginx或者apache、tomcat等web代理服务器中,同时要根据 自己服务器的项目路径 更改react的路由地址。
如果说项目是直接跟在域名后面的,比如:http://www.sosout.com ,根路由就是 '/'。
如果说项目是直接跟在域名后面的一个子目录中的,比如:http://www.sosout.com/children ,根路由就是 '/children ',不能直接访问index.html。

以配置Nginx为例,配置过程大致如下:
(假设:
1、项目文件目录: /mnt/html/reactAntd(reactAntd目录下的文件就是执行了npm run dist 后生成的antd目录下的文件)
2、访问域名:antd.sosout.com
进入nginx.conf新增如下配置:

server {
    listen 80;
    server_name  antd.sosout.com;
    root /mnt/html/reactAntd;
    index index.html;
    location ~ ^/favicon\.ico$ {
        root /mnt/html/reactAntd;
    }

    location / {
        try_files $uri $uri/ /index.html;
        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-Forwarded-Proto  $scheme;
    }
    access_log  /mnt/logs/nginx/access.log  main;
}

注意事项:
1、配置域名的话,需要80端口,成功后,只要访问域名即可访问的项目
2、如果你使用了react-router的browserHistory 模式,在nginx配置还需要重写路由:

server {
    listen 80;
    server_name  antd.sosout.com;
    root /mnt/html/reactAntd;
    index index.html;
    location ~ ^/favicon\.ico$ {
        root /mnt/html/reactAntd;
    }

    location / {
        try_files $uri $uri/ @fallback;
        index index.html;
        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-Forwarded-Proto  $scheme;
    }
    location @fallback {
        rewrite ^.*$ /index.html break;
    }
    access_log  /mnt/logs/nginx/access.log  main;
}

为什么要重写路由?因为我们的项目只有一个根入口,当输入类似/home的url时,如果找不到对应的页面,nginx会尝试加载index.html,这是通过react-router就能正确的匹配我们输入的/home路由,从而显示正确的home页面,如果browserHistory模式的项目没有配置上述内容,会出现404的情况。

basename: string
作用:为所有位置添加一个基准URL
使用场景:假如你需要把页面部署到服务器的二级目录,你可以使用 basename 设置到此目录。

<BrowserRouter basename="/calendar"/>
<Link to="/today"/> // renders <a href="/calendar/today">

clipboard.png

疑惑:
为什么路由上带有index.html?不管是browserHistory还是HashHistory 遇到index.html 都会重定向,而且也不美观!

<BrowserRouter basename="/demo/index.html/" />

为什么不直接改webpack的配置? 应该是publicPath吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题