Preface
In the project, if usedvue-router
And the routing mode is set tohistory
Mode, you may encounter a 404 error when refreshing the page or directly accessing a route. This is becausehistory
In mode, the path of the front-end route does not match the actual path on the server, causing the server to be unable to find the corresponding resource.
Solution
To resolve this issue, you need to redirect all requests to, let the front-end application take over the routing logic.
1. Nginx configuration
If you use Nginx as your server, you can configure it as follows:
server { listen 80; server_name ; root /path/to/your/dist; # Static file path after your Vue project is packaged index ; location / { try_files $uri $uri/ /; } }
-
try_files $uri $uri/ /;
: This directive tells Nginx to try the requested URI first. If it cannot be found, it will return, processed by front-end routing.
2. Apache configuration
If you use Apache as your server, you can create or modify.htaccess
document:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / # If the requested file exists, provide the file directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # If the file does not exist, redirect to RewriteRule . / [L] </IfModule>
3. Use the hash mode
If you don't want to change the server configuration, you can consider using Vue Router'shash
model. This pattern will be added to the URL#
,For example/#/about
. This method will not have any problem with refreshing 404, because#
The subsequent content will not be sent to the server.
existrouter/
In the meantime, willmode
Set tohash
:
const router = new VueRouter({ mode: 'hash', routes: [ // Your routing configuration ] });
Summarize
-
history
Mode: It needs to be configured on the server side to ensure that all routes are redirected to。
-
hash
Mode: simpler, no server-side configuration is required, but there will be a URL#
。
Choose the right solution based on your project requirements and server environment.
This is the end of this article about the error of refreshing 404 in vue project page. For more related content of refreshing 404 in vue page page, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!