第一步: 下載 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