vue、、react等单页面项目应该这样子部署到服务器等单页面项目应该这样子部署到服务器
最近好多伙伴说,我用vue做的项目本地是可以的,但部署到服务器遇到好多问题:资源找不到,直接访问index.html页面空
白,刷新当前路由404。。。现在我们一起讨论下单页面如何部署到服务器?
由于前端路由缘故,单页面应用应该放到nginx或者apache、tomcat等web代理服务器中,千万不要直接访问index.html,同时
要根据自己服务器的项目路径更改react或vue的路由地址。
如果说项目是直接跟在域名后面的,比如:http://www.sosout.com ,根路由就是 ‘/’。
如果说项目是直接跟在域名后面的一个子目录中的,比如:http://www.sosout.com/children ,根路由就是 ‘/children ‘,不能直
接访问index.html。
以配置Nginx为例,配置过程大致如下:(假设:
1、项目文件目录: /mnt/html/spa(spa目录下的文件就是执行了npm run dist 后生成的dist目录下的文件)
2、访问域名:spa.sosout.com)
进入nginx.conf新增如下配置:
server {
listen 80;
server_name spa.sosout.com;
root /mnt/html/spa;
index index.html;
location ~ ^/favicon\.ico$ {
root /mnt/html/spa;
}
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 模式或 vue-router的 history 模式,在nginx配置还需要重写路由:
server {
listen 80;
server_name spa.sosout.com;
root /mnt/html/spa;
index index.html;
location ~ ^/favicon\.ico$ {
root /mnt/html/spa;
}
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模
评论0
最新资源