Vue預設的router模式是hash mode,所以我們能設定成history mode,來去除URL中的#(hashtag),但是除了http://localhost/ 首頁能夠正常顯示,直接打開其他網址會出現404 page no found的錯誤訊息。
const router = new VueRouter({
mode: 'history',
routes: [...]
})也就是說其實在vue專案裡面實際存在的只有index.html這個頁面,我們必須透過apache設定,將其他網址導到index.html,就能用所有的URL正常的顯示網頁。
Ubuntu設定方式
方法一、mod_rewrite模組
1. 請先確定已經啟用mod_rewrite 模組
$ sudo a2enmod rewrite
2. 編輯apache的config
# /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
...
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
3. 在專案目錄下新增檔案.htaccess
# /var/www/html/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
目錄架構如下
/var/www/html ├── .htaccess ├── index.html └── static
4. 重啟apache2
$ sudo systemctl restart apache2
方法二、FallbackResource
與方法一相同,只是.htaccess內容改用fallbackresource,目的一樣是改寫URL導向index.html。
# /var/www/html/.htaccess FallbackResource /index.html存檔後再重啟apache2就大功告成囉!
參考資料:
https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations
沒有留言:
張貼留言