nginx配置 vue打包後的項目 解決刷新頁面404問題|nginx配置多端訪問

訪問vue頁面時,/# 使url看着不美觀,使用 H5 history模式能夠完美解決這個問題,但須要後端nginx幫助。接下來咱們本身配置一下。html

使用前端路由,但切換新路由時,想要滾動到頁面頂部,或者保持原先的滾動位置,就像從新加載頁面那樣,vue-router 能夠讓你自定義路由切換頁面時如何滾動。前端

當建立Router實例時,能夠提供一個 scrollBehavior 方法:vue

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…android

打包以後會形成一個問題,刷新打包文件頁面 ,會出現404頁面空白,接下來須要配置一下nginx文件,就能夠訪問打包後的文件了。nginx

vue單頁面的啓動頁面是index.html文件,路由實際是不存在的,因此會出現頁面刷新404問題,須要設置一下訪問vue頁面映射到index.html上。vue-router

首先,咱們須要肯定一下打包靜態資源的路徑須要設置絕對路徑windows

config/index.js後端

build: {
	assetsPublicPath: '/'
}
複製代碼

而後配置一下nginx映射問題api

location / {
    root   /www/dist;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;  //映射到index.html上
}
複製代碼

醬紫就能夠訪問啦。服務器

有同窗可能會遇到 nginx 配置pc端、移動端自動跳轉的問題, 接下來咱們配置一下。

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;
    
    server {
        listen       80;
        server_name  www.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
            }
            index  index.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_size   2m;
            proxy_connect_timeout      90;
            proxy_send_timeout         90;
            proxy_read_timeout         90;
            proxy_buffer_size          4k;
            proxy_buffers              4 32k;
            proxy_busy_buffers_size    64k;
            proxy_temp_file_write_size 64k;
            client_max_body_size       5m;
        }  
        error_page  404              http://www.baidu.com;
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }
複製代碼

醬紫就能夠使用同一網址同時訪問移動端和pc端項目啦。

有些地方可能表述的不夠清晰,又不懂的地方能夠留言,我看到知道後必定會及時回答的。

相關文章
相關標籤/搜索