404s with Vue Router URLs in Apache
In my most recent personal project, I used the Vue framework and Vue Router to handle the routing. I host the site on Apache and it uses the mod_rewrite module to rewrite URLs. The only rewrite rules I initially had were to redirect all requests to HTTPS and to prevent hot-linking of any images.
Within the application, links to different pages were correctly handled by Vue Router. However, if I were to use the links directly in the address bar, I would get a 404 error. This is because Apache, and not Vue Router, was attempting to handle the URL.
To fix this, I had to update my rewrite rules to redirect certain requests to the index page so that Vue Router could
handle the URLs. I added the following rules to my .htaccess
file:
<IfModule mod_rewrite.c>
RewriteEngine On # enable the rewrite engine
RewriteBase / # set the base URL for relative paths
# Other rules go in here ...
RewriteRule ^index\.html$ - [L] # don't rewrite index.html
RewriteCond %{REQUEST_FILENAME} !-f # if file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-d # or if directory doesn't exist
RewriteRule . index.html [L] # serve index.html
</IfModule>
This was a simple fix and now the URLs to separate pages in the application do not return 404 errors when entered directly in the address bar.