【XAMPP】【Apache】SPA部署時遇到的問題 導頁機制

使用Apache在部署SPA網站時
若進入到一些不存在的頁面、重整等操作,網頁很容易脫離SPA的掌控

這邊以Docusaurus文檔網站為例子




希望只要在該域名底下,若沒有此頁面、查無資料、路徑錯誤時
都導到Docusaurus預設的404頁面"找不到頁面"

Page Not Found

We could not find what you were looking for.

Please contact the owner of the site that linked you to the original URL and let them know their link is broken.




而非Apache內建回傳的


404

Not Found

The requested URL was not found on this server.


Apache/2.4.54 (Win64) OpenSSL/1.1.1p PHP/7.4.30 Server at gjlmotea.com Port 443


403

Forbidden

You don't have permission to access this resource.


Apache/2.4.54 (Win64) OpenSSL/1.1.1p PHP/7.4.30 Server at gjlmotea.com Port 443







解決方式

在Apache設定加入DirectoryIndex、ErrorDocument
在網址搜尋不到檔案時,能轉到指定的位置去

(直接從設定改而不加在.htaccess檔案中,因為我無法為每個文檔目錄都一一建置htaccess)

httpd-ssl.conf
```
<VirtualHost *:443>
    DocumentRoot "C:\www\yuyuGoal\docs"
    ServerName docs.yuyuGoal.com:443
    ServerAlias doc.yuyuGoal.com docs.yuyuGoal.com
    SSLEngine on
    SSLCertificateFile "C:\Certbot\live\yuyuGoal.com\cert.pem"
    SSLCertificateKeyFile "C:\Certbot\live\yuyuGoal.com\privkey.pem"
    SSLCertificateChainFile "C:\Certbot\live\yuyuGoal.com\chain.pem"
    DirectoryIndex index.html /404.html
    ErrorDocument 404 /404.html
</VirtualHost>
```

當使用者輸入網址,此網址對應到資料夾時 會開啟DirectoryIndex指定的檔案
若指定檔案不存在,DirectoryIndex 會依序開啟aaa.html、bbb.html... 直到檔案存在 否則則呈現403 Forbidden

Docusaurus build好之後的目錄結構會是這樣子,已經備妥index.html404.html



此處這樣子加,是希望先去看資料夾內有無index.html,如果沒有的話再去404
(否則一進文檔首頁的話,因為根目錄也是目錄資料夾,所以會先被跳到404瞬間在跳轉回來當前頁面)

ErrorDocument則是在伺服器無法正確回應的時候處理的錯誤
可以對不同的錯誤狀態做不同回傳
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html


因為架設Docusaurus時遇到頁面閃爍(路徑跳轉)的問題
需移除 docusaurus.config.js 中的 trailingSlash 這行設定

沒有留言:

張貼留言