Angular应用默认采用HashHistory方式进行路由,若要支持“伪多页”的BrowserHistory方式,需要结合Nginx的配置。
过程如下:
1、在路由设置中,修改路由配置
javascriptCopy code- 1
- 2
- 3
RouterModule.forRoot(routes, {
useHash: false
})
RouterModule.forRoot(routes, {
useHash: false
})
2、配置Nginx
nginxCopy code- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
server {
listen 80;
server_name www.app.com;
location / {
proxy_pass https://cdn.com/path/index.html;
}
location /app/ {
proxy_pass https://cdn.com/path/index.html;
try_files $uri $uri/ /;
}
location ~* /app/(.+\..+$) {
proxy_pass https://cdn.com/path/$1;
}
location /api/ {
proxy_set_header Host www.app.com;
proxy_pass http://server.app.com/api/;
}
}
server {
listen 80;
server_name www.app.com;
location / {
proxy_pass https://cdn.com/path/index.html;
}
location /app/ {
proxy_pass https://cdn.com/path/index.html;
try_files $uri $uri/ /;
}
location ~* /app/(.+\..+$) {
proxy_pass https://cdn.com/path/$1;
}
location /api/ {
proxy_set_header Host www.app.com;
proxy_pass http://server.app.com/api/;
}
}
3、绑定Hosts
www.app.com 127.0.0.1
4、重启nginx
访问www.app.com
即可看到效果。
注:
- base设置为“/app/”;
- 本地启动:
ng serve --deploy-url /app
- 替换nginx配置中的
www.app.com
、cdn.com/path
、server.app.com
为实际的域名、路径。