nginx配置 vue打包後的專案 解決重新整理頁面404問題|nginx配置多端訪問
訪問vue頁面時,/# 使url看著不美觀,使用 H5 history模式可以完美解決這個問題,但需要後端nginx幫助。接下來我們自己配置一下。
使用前端路由,但切換新路由時,想要滾動到頁面頂部,或者保持原先的滾動位置,就像重新載入頁面那樣,vue-router 可以讓你自定義路由切換頁面時如何滾動。
當建立Router例項時,可以提供一個 scrollBehavior 方法:
const router = new VueRouter({ routes: [...], mode: 'history', //H5 history模式 scrollBehavior (to, from, savedPosition) { // return 期望滾動到哪個的位置 return { x: 0, y: 0 } //讓頁面滾動到頂部 } }) 複製程式碼
更多滾動行為例項可以參考官網router.vuejs.org/zh/guide/ad…
打包之後會造成一個問題,重新整理打包檔案頁面 ,會出現404頁面空白,接下來需要配置一下nginx檔案,就可以訪問打包後的檔案了。
vue單頁面的啟動頁面是index.html檔案,路由實際是不存在的,所以會出現頁面重新整理404問題,需要設定一下訪問vue頁面對映到index.html上。
首先,我們需要確定一下打包靜態資源的路徑需要設定絕對路徑
config/index.js
build: { assetsPublicPath: '/' } 複製程式碼
然後配置一下nginx對映問題
location / { root/www/dist; indexindex.html index.htm; try_files $uri $uri/ /index.html;//對映到index.html上 } 複製程式碼
醬紫就可以訪問啦。
有同學可能會遇到 nginx 配置pc端、移動端自動跳轉的問題, 接下來我們配置一下。
http { includemime.types; default_typeapplication/octet-stream; sendfileon; keepalive_timeout65; server { listen80; server_namewww.baidu.com; //伺服器網址 set $mobile_rewrite do_not_perform; //設定pc重定向 if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os )?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino") { set $mobile_rewrite perform; } //設定移動端重定向 location / { root/www/dist/m; //移動端root if ($mobile_rewrite = do_not_perform) { //根據重定向 重置 root root /www/dist; //pc端root } indexindex.html index.htm; try_files $uri $uri/ /index.html; //對映到index.html上 } location ~ ^/api { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/dev/official/official.sock; proxy_max_temp_file_size2m; proxy_connect_timeout90; proxy_send_timeout90; proxy_read_timeout90; proxy_buffer_size4k; proxy_buffers4 32k; proxy_busy_buffers_size64k; proxy_temp_file_write_size 64k; client_max_body_size5m; } error_page404http://www.baidu.com; error_page500 502 503 504/50x.html; location = /50x.html { roothtml; } } 複製程式碼
醬紫就可以使用同一網址同時訪問移動端和pc端專案啦。
有些地方可能表述的不夠清晰,又不懂的地方可以留言,我看到知道後一定會及時回答的。