Nginx配置单页应用的代理
小布丁 2017-08-01 工具配置
SPA(单页应用)可以说是这几年前端领域的一个技能栈了。单页应用不同与传统的多页面应用,顾名思义,单页应用整个应用架构中只有一个实际页面运行,再借助于H5的History API或hash路由来实现前端路由,从而实现了前后端的解耦,或者前后端分离。不同于以前,前端页面都是放在后端项目的模板目录下的,由服务端来渲染模板,并且由后端路由来决定一个请求应该渲染哪个模板,可以说前端对后端的依赖是非常大的。 单页应用实现了前后端分离,页面的渲染与路由跳转都由前端同学自行控制,后端只提供API接口。这种模式下看似前端同学实现了一个大独立,但是很多同学面对这种开发模式完全不知道如何搭建开发环境以及线上部署。开发环境的搭建一般来说比较简单,常见的单页应用框架都提供了脚手架,比如vue的vue-cli,只需要安装后,一个vue create project就可以初始化一个项目,然后就可以开发了。部署方面利用Nginx做代理
# history模式
server {
listen 80;
server_name www.xxx.cn;
access_log /data/log/nginx_log/xxxx.access.log main;
error_log /data/log/nginx_log/xxxx_error.log warn;
#history模式
location / {
#项目路径
root /data/www;
try_files $uri $uri/ /index.html;
# hiostory 模式 防止Vue 应用刷新页404
if ( !-f $request_filename ) {
rewrite ^/(.*) /index.html break;
}
}
# 数据接口代理
location /api/{
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://www.baidu.com/;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# hash模式
server {
listen 000;
server_name xxxx.xxx.cn;
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
client_max_body_size 1000m;
# 静态资源代理
location / {
root /data/www;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
#数据接口代理
location /huiApi/ {
rewrite ^/huiApi/(.*)$ /$1 break;
proxy_pass http://www.baidu.com/;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 二级目录
server{
#二级目录 部署应用 --静态资源位置代理
location /hmr {
root /data/www;
if ( !-f $request_filename ) {
rewrite ^/(.*) /hmr/index.html break;
}
}
#数据接口代理
location /huiApi/ {
rewrite ^/huiApi/(.*)$ /$1 break;
proxy_pass http://www.baidu.com;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17