nginx中部署发布angular应用
注:Angular应用可以ng buid 编译成静态页面,然后部署在任何 web 服务器上,这里仅仅是选择nginx而已,同时编译后的文件其实就仅仅是静态文件而已,与其它 html 文件本质上无异。
一、编译
前提: 请确保@angular/cli已经安装
假设angular项目名称为new-app
在项目主目录下输入以下命令:
ng build
项目目录下生成了新的目录dist及其下的new-app子文件/目录,此时则成功将应用编译成静态资源。
二、部署
原则上,您可以将这些资源拷贝到任何项目中,比如apache 、JavaWeb、NodeJs等项目中,它们同样的可以运行。
前提: 服务器已经安装nginx,并假设nginx安装目录为/usr/local/nginx
nginx 的部分相关命令:
- nginx : 启动服务
- nginx -s stop : 先查出 nginx 进程 id,然后使用 kill 命令强制杀掉进程
- nginx -s quit : 等待 nginx 进程处理任务完毕,然后再进行停止
- nginx -s reload : 重启服务
- ps aux|grep nginx : 查看 nginx 进程
1) 准备源文件
拷贝dist目录下的所有文件到服务器上,比如拷贝至/data/web/
2) 配置nginx
sudo vi /usr/local/nginx/conf/nginx.conf
这里设置80端口为web页面服务,该端口需要root权限启动nginx.
server配置如下:
server {
listen 80;
server_name localhost;
location / {
root /data/app/sys/ptt-front-ng/ptt-front;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
必须设置 使用 try_files 指向 index.html
需要server location 配置 try_files $uri $uri/ /index.html;
否则angular的路由跳转无效,会出现404错误
try_files用法介绍
参考https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#front-controller-pattern-web-apps
启动nginx
sudo /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
然后浏览器访问即可。