Vue Router return 404 when revisit to the url
I think you are missing that SPA is not server side rendering. At least for the majority. So, when you access /anything your web server won't redirect it to index.html. However, if you click on any vuejs router link, it will work due to the fact that the javascript got in action, but not the server side.
To solve this, use .htaccess and redirect all requests to index.html like so
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</ifModule>
Hope it helps someone!
By refreshing the page you are making a request to the server with the current url and the server returns 404. You have to handle this on your web framework or web server level.
https://router.vuejs.org/en/essentials/history-mode.html
Even better (on Ubuntu) if you have root access would be to modify /etc/apache2/apache2.conf
, since even Apache themselves discourage the use of .htaccess
under such circumstances.
Note that first, you have to do
sudo a2enmod rewrite
Then, add the following block to /etc/apache2/apache2.conf
:
<Directory /var/www/html/>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</Directory>
After this, do
sudo systemctl restart apache2
For me, this works flawlessly, as it not just redirects routes created by Vue back to /
, but actually refreshes the website to the same route, so you're still on the same view after refreshing.