# Nuxt3js Nginx 重定向404問題 ## 注意事項 - 如果想要nginx只向想要的子目錄,那麼必須在location只向你要的目錄,並且在nuxt.config.ts中需要把baseUrl設為子目錄名稱。 舉個例子,我想要網址為 ***http://localhost/subnode/index.html*** - 其中**subnode**為子目錄 ### 實現方法 - nuxt配置 ```ts= // nuxt.config.ts app: { baseURL: "/subnode", }, ``` - nginx配置 ```json= //nginx.conf location /subnode/ { root html; # 網站目錄 #alias html; try_files $uri $uri/ /subnode/index.html; } ``` ### SPA單頁跳轉回定向畫面 - 在某些情況中,我們可能需要使用SPA模式,然後讓使用者在畫面中去跳轉到其他分頁,在NUXT上部屬完成後瀏覽跳轉頁面都沒問題,但你會發現在子分頁時按下F5刷新畫面會變成404,這時你就會思考,奇怪我進來的網址式沒問題的,畫面都出來了,為何重整一下變成404。這是因為NUXT的封裝方式有關,實際上這個路由是被應用創建出來的,而真實的檔案路徑中根本沒有這個路徑,所以導致NGINX解析時直接去尋找實際的目錄那當然是找不到拉,所以跳404囉! ### 解決方案 - **當畫面進入404時,直接定向nuxt應用。** - 沒錯就是這麼單純,當判斷到404畫面直接重新導向index.html也就是nuxt應用的進入點,這樣讓導向重新進入應用,等於把控制權交付給nuxt了。 - nuxt配置 ```ts= // nuxt.config.ts app: { baseURL: "/", //記得設定成'/',除非你是上面的那種需要子目錄的情況。 }, ``` ```json= //nginx.conf location / { root html; # 網站目錄 try_files $uri $uri/ /index.html; # 重定向到nuxt的應用 } ``` ### 排坑 - nginx配置中/前後必須為半形空格,已經彩雷好幾次複製貼上沒有注意格式。 - " / " 和 " / "看似一樣其實不同。 ```json= //nginx.conf location / { root html; # 網站目錄 index index.html index.htm; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up