第一步: 下载 nginx
下载后,将其解压到 本地的任一目录下。
此时我们可以看到有如下目录:
html路径下放置我们前端 build好的代码(如何build,相信各位都会),conf下有个非常重要的文件nginx.conf,用来配置nginx服务器。
第二步: 配置nginx服务器
打开nginx.conf文件,直接找到配置server 的地方,取消掉暂时用不到的配置,下面便是我的配置:
server {
# 启动后的端口
listen 8880;
# 启动时的地址
server_name localhost;
# 启动后,地址栏输入: localhost:8880, 默认会在html文件夹下找 index.html文件
location / {
root html;
index index.html;
}
# 404页面配置,页面同样在html文件夹中
error_page 404 /404.html;
location = /404.html {
root html;
}
# 其他错误码页面配置
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# 配置代理。由于项目是在本地起动的,而我们的request需要请求其他ip地址。如果你的request链接为localhost:8880/abc/login?name=12345,那么下面配的就是location /abc
location /api {
proxy_pass http://192.168.0.0:80;
}
# 一把前端不管用vue,还是react等框架,默认都是单页面的,如果你的项目是多页面的,则需要用到下面的配置。
# 因为此时你的浏览器的url不是localhost:8880/#/login,而是 localhost:8880/a.html/#/login
# 所以我们需要将路径中a.html指向具体的html文件夹中的文件,因为默认是index.html
location /a.html {
alias html;
index a.html;
}
location /b.html{
alias html;
index b.html;
}
}
第三步: 将build好的内容放到nginx下的html文件夹下
只需要dist下的内容,如
第四步: 启动nginx服务器
在
路径下右键,打开命令号工具,并输入
>start nginx
然后在浏览器地址栏输入
localhost:8880
即可
第五步: 停止nginx服务器
>nginx -s stop
注意事项
1、在修改nginx.conf文件时,每行的末尾必须带有分好";",否则会报错。2、有些命令行工具在执行start nginx后,一闪而过,所以你并不知道到底启动了还是没有,可以运行下面的命令:
tasklist /fi "imagename eq nginx.exe"
结果类似于这样
3、如果你运行nginx -s stop命令后,再次运行tasklist /fi "imagename eq nginx.exe"命令发现还是有进程,并没有停止,可以访问任务管理器,然后结束进程