Vue.js 404 Error Fix
March 9, 2025 Β· AI Conversations
### **Solution for Laravel + Vue.js (Inertia.js)**
Since you're using Laravel with Vue.js and Inertia.js, you need to configure Laravel to handle Vue routes properly.
#### **1. Update Laravel Routes**
Make sure your Laravel routes serve the Vue app for unknown routes.
use IlluminateSupportFacadesRoute;
use InertiaInertia;
Route::get('/{any}', function () {
return Inertia::render('App');
})->where('any', '.*');
This ensures that Laravel serves the Vue application for any undefined route.
—
#### **2. Check Vue Router Mode**
In your `router.js` file, ensure that Vue Router is using **history mode**.
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact },
],
});
export default router;
If you're using `createWebHashHistory()`, the issue won't occur, but URLs will contain `#/`, which isn't ideal for SEO.
—
#### **3. Configure Apache (if using it)**
Since you're using **Apache on AWS EC2**, update your `.htaccess` file in the **public** folder:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
</IfModule>
This ensures that all requests are redirected to Laravel, which then serves the Vue app.
—
#### **4. Configure Nginx (if using it)**
If your server is running **Nginx**, update your Nginx config:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
—
### **Final Steps**
– **Clear caches:**
php artisan config:clear
php artisan route:clear
– **Restart Apache/Nginx:**
sudo systemctl restart apache2 # For Apache
sudo systemctl restart nginx # For Nginx
This should resolve the **404 error on page refresh** in your Vue.js + Laravel + Inertia.js application. π Let me know if you need further assistance!
works well in local but in production on page referesh it give 404 error
—
### **Solution Based on Your Hosting Environment**
#### **1. If Using Apache**
You need to configure the `.htaccess` file to redirect all requests to `index.html`, which Vue can then handle.
π **Create or edit your `.htaccess` file in the root folder (where `index.html` is located)**:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
This ensures that any unknown route is redirected to `index.html`, allowing Vue Router to handle the request.
—
#### **2. If Using Nginx**
Modify your **Nginx configuration** to serve `index.html` for all routes:
π **Edit your Nginx config file (usually in `/etc/nginx/sites-available/default` or `/etc/nginx/conf.d/default.conf`)**:
server {
listen 80;
server_name yourdomain.com;
root /var/www/html/dist; # Change to your Vue build folder
index index.html;
location / {
try_files $uri /index.html;
}
location /assets/ {
try_files $uri =404;
}
}
π **Restart Nginx after making changes:**
sudo systemctl restart nginx
—
#### **3. If Using Vite with Static Hosting (Netlify, Vercel, Firebase, etc.)**
If your Vue app is built with **Vite**, most static hosts require a special redirect configuration.
– **Netlify:** Create a `_redirects` file inside `dist/` with the following:
/* /index.html 200
– **Vercel:** Add a `vercel.json` file:
{
"rewrites": [
{ "source": "/(.*)", "destination": "/index.html" }
]
}
– **Firebase:** Add this to `firebase.json`:
{
"hosting": {
"rewrites": [
{ "source": "**", "destination": "/index.html" }
]
}
}
—
#### **4. Check Vue Router Configuration**
Make sure your **Vue Router** is using history mode properly:
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(), // Make sure this is not 'createWebHashHistory()'
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact },
],
});
export default router;
π **If you use `createWebHashHistory()`, the issue wonβt occur, but URLs will have `#/` (e.g., `/#/about`).**
—
### **Final Steps**
1. **Rebuild the project**
npm run build
2. **Deploy the `dist/` folder to your server**
3. **Restart the web server**
4. **Test by refreshing a route (e.g., `/about`)** β
—
### **Summary**
β If using **Apache** β Add `.htaccess`
β If using **Nginx** β Update `nginx.conf`
β If using **Netlify/Vercel/Firebase** β Add the appropriate rewrite rules
β **Ensure Vue Router uses `createWebHistory()`**
This will **fix the 404 error on page refresh** in your Vue.js production build. Let me know if you need further help! π
import HomeView from '../views/HomeView.vue'
import Youtubeiew from '@/views/Youtubeiew.vue'
import NewsView from '@/views/NewsView.vue'
import LoginView from '@/views/LoginView.vue'
import RegisterView from '@/views/RegisterView.vue'
import DashboardView from '@/views/User/DashboardView.vue'
import ProfileView from '@/views/User/ProfileView.vue'
import SettingsView from '@/views/User/SettingsView.vue'
import { useAuthStore } from '@/stores/auth';
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView,
},
{
path: '/news',
name: 'news',
component: NewsView,
},
{
path: '/youtube',
name: 'youtube',
component: Youtubeiew,
},
{
path: '/login',
name: 'login',
component: LoginView,
},
{
path: '/register',
name: 'register',
component: RegisterView,
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/AboutView.vue'),
},
{
path: '/dashboard',
name: 'dashboard',
component: DashboardView,
meta: { requiresAuth: true },
},
{
path: '/profile',
name: 'profile',
component: ProfileView,
meta: { requiresAuth: true },
},
{
path: '/settings',
name: 'settings',
component: SettingsView,
meta: { requiresAuth: true },
},
],
})
router.beforeEach((to, from, next) => {
const authStore = useAuthStore();
if (to.meta.requiresAuth && !authStore.token) {
next('/login'); // Redirect if not logged in
} else {
next();
}
});
export default router
—
### **Fixing 404 on Page Refresh in Production**
### **1. Fix the Typo in Your Code**
There's a **typo** in your import for `YoutubeView.vue`:
import Youtubeiew from '@/views/Youtubeiew.vue'
β Change it to:
import YoutubeView from '@/views/YoutubeView.vue'
—
### **2. Configure Your Web Server (Choose Based on Your Setup)**
#### **Apache (For Shared Hosting or VPS)**
Create or update your **`.htaccess`** file in the `dist/` directory:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
β **Restart Apache**:
sudo systemctl restart apache2
—
#### **Nginx (For VPS or Dedicated Server)**
Modify your **Nginx configuration** (`/etc/nginx/sites-available/default` or `/etc/nginx/nginx.conf`):
server {
listen 80;
server_name yourdomain.com;
root /var/www/html/dist; # Change this to your Vue build folder
index index.html;
location / {
try_files $uri /index.html;
}
location /assets/ {
try_files $uri =404;
}
}
β **Restart Nginx**:
sudo systemctl restart nginx
—
#### **Netlify (For Static Hosting)**
Create a `_redirects` file in the **`dist/`** folder:
/* /index.html 200
—
#### **Vercel (For Serverless Hosting)**
Create a `vercel.json` file:
{
"rewrites": [
{ "source": "/(.*)", "destination": "/index.html" }
]
}
—
#### **Firebase Hosting**
Modify `firebase.json`:
{
"hosting": {
"rewrites": [
{ "source": "**", "destination": "/index.html" }
]
}
}
—
### **3. Rebuild and Deploy**
After applying the fix for your hosting type, **rebuild and deploy** your Vue project:
npm run build
Then **upload the `dist/` folder** to your server.
—
### **Final Checklist**
β **Fix Typo in Vue Router Imports**
β **Set Up Apache/Nginx Rewrite Rules**
β **Add Redirects for Static Hosting**
β **Rebuild and Deploy Your Vue App**
After these steps, refreshing any route (`/dashboard`, `/profile`, etc.) should work **without a 404 error**! π Let me know if you need further assistance.
—
## **1. Confirm the Build Directory and Deployment**
Since you're using **Vue Router with `createWebHistory()`**, ensure your build is properly deployed.
Run:
npm run build
This should generate a **`dist/` folder** containing the necessary static files. Make sure you **deploy the contents of the `dist/` folder**, not the entire Vue project.
—
## **2. Check Server Setup Based on Your Hosting Environment**
### **Apache (Shared Hosting or VPS)**
If you're hosting on Apache, ensure your `.htaccess` file is inside the **`dist/`** directory.
π **Create or update `.htaccess` in `dist/`:**
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
π **Restart Apache:**
sudo systemctl restart apache2
—
### **Nginx (For VPS or Dedicated Server)**
If using **Nginx**, ensure your configuration file is properly set up.
π **Edit Nginx configuration (`/etc/nginx/sites-available/default` or `/etc/nginx/nginx.conf`):**
server {
listen 80;
server_name yourdomain.com;
root /var/www/html/dist; # Ensure this points to your Vue build folder
index index.html;
location / {
try_files $uri /index.html;
}
location /assets/ {
try_files $uri =404;
}
}
π **Restart Nginx:**
sudo systemctl restart nginx
—
### **3. Check If the Server Is Serving the Correct Files**
Run:
ls -l /var/www/html/dist
Ensure your **`index.html` and `assets/` folder** exist inside `/var/www/html/dist`.
Try **accessing `index.html` manually** by visiting:
http://yourdomain.com/index.html
β If it loads fine but **routes like `/dashboard` still return 404**, then your rewrite rules aren't applied.
—
### **4. Verify Router Mode and Base URL**
Check your **Vue Router setup** inside `router.js`:
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), // Ensure BASE_URL is set correctly
routes: [
{ path: '/', component: HomeView },
{ path: '/dashboard', component: DashboardView, meta: { requiresAuth: true } },
],
});
π **Check `vite.config.js`:**
Ensure you have the correct `base` set:
export default defineConfig({
base: '/',
plugins: [vue()],
})
If you're deploying to a subdirectory (e.g., `yourdomain.com/app/`), set `base: '/app/'` in `vite.config.js`.
—
### **5. Test With Different Router Modes**
If nothing else works, switch to `createWebHashHistory()` (temporary fix):
import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(), // Uses hash-based routing (e.g., /#/dashboard)
routes: [...],
});
This avoids server-side issues but adds `#` to URLs.
—
### **6. Clear Cache and Try Again**
If you've applied fixes but the error persists:
– **Clear browser cache**
– **Restart the server**
– **Try opening a private/incognito window**
—
## **Final Summary**
β
**Ensure `dist/` is correctly deployed**
β
**Configure Apache/Nginx to redirect all requests to `index.html`**
β
**Verify Router is using `createWebHistory()` with correct `base`**
β
**Try switching to `createWebHashHistory()` for debugging**
β
**Clear cache and restart the server**
If the problem persists, let me know your **hosting type** and **server logs** so we can debug further! π
—
### **1. Identify Where the Issue Occurs**
Try these steps in the browser:
β
**Go to your domain manually** (`https://yourdomain.com`).
β
**Navigate to a route** (e.g., `/dashboard`).
β
**Press F12 > Network Tab > Refresh Page** and check:
– If the request to `/dashboard` returns **404**, itβs a server issue.
– If the page loads correctly after clicking links (but not on refresh), itβs a routing issue.
—
### **2. Ensure Your Vue Build is Correct**
Run:
npm run build
Check if `dist/` contains:
index.html
assets/
js/
css/
favicon.ico
If `dist/` is empty or missing files, delete `dist/` and rebuild:
rm -rf dist
npm run build
—
### **3. Check Your Server Type & Apply Fixes**
Depending on where you're hosting your Vue app, you need different fixes.
#### **β Apache (Shared Hosting or
files in vuefront/dist
we have created this
Alias /frontend /var/www/vuefront/dist
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
—
## **π 1. Problem Diagnosis**
With your current setup:
– `/frontend` (loads `index.html` correctly β
)
– `/frontend/news` (404 on refresh β)
### **π‘ Why does this happen?**
When you refresh `/frontend/news`, Apache tries to find `/var/www/vuefront/dist/news`, but no such file exists. Vue is handling routes **client-side**, but Apache isn't redirecting all requests to `index.html`.
—
## **π§ 2. Fix: Add Apache Rewrite Rules**
### **Solution: Modify Apache VirtualHost**
You need to tell Apache to **redirect all unknown routes to `index.html`**.
### **Edit Apache Configuration**
Run:
sudo nano /etc/apache2/sites-available/000-default.conf
Then, update it like this:
Alias /frontend /var/www/vuefront/dist
<Directory /var/www/vuefront/dist>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
RewriteEngine On
RewriteBase /frontend
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /frontend/index.html [L]
</Directory>
### **Restart Apache**
sudo systemctl restart apache2
—
## **π 3. Create `.htaccess` in `dist/`**
Inside `/var/www/vuefront/dist/`, create or update `.htaccess`:
sudo nano /var/www/vuefront/dist/.htaccess
Add the following:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /frontend
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
### **Restart Apache Again**
sudo systemctl restart apache2
—
## **π 4. Verify Everything**
### β
**Test these cases:**
| Action | Expected Outcome |
|———|—————-|
| Open `http://your-ec2-ip/frontend/` | Loads Vue app β
|
| Open `http://your-ec2-ip/frontend/news` | Loads Vue app β
|
| Refresh on `/frontend/news` | **No 404 error** β
|
If the issue persists, **clear cache**:
sudo systemctl restart apache2
or
sudo service apache2 restart
and test again.
—
### **Final Summary**
β
**Apache must redirect all unknown routes to `index.html`**
β
**Added rewrite rules in Apache config and `.htaccess`**
β
**Restarted Apache & Cleared Cache**
Try this and let me know if you're still getting a 404 on refresh! π
—
## **1οΈβ£ Check If Apache Mod_Rewrite Is Enabled**
First, confirm that **mod_rewrite** is enabled on Apache. Run:
sudo a2enmod rewrite
sudo systemctl restart apache2
Then, test if `mod_rewrite` is active:
apachectl -M | grep rewrite
If you donβt see `rewrite_module`, enable it again and restart Apache.
—
## **2οΈβ£ Update Apache VirtualHost Configuration**
Make sure your Apache configuration correctly **redirects all Vue.js routes to `index.html`**.
Run:
sudo nano /etc/apache2/sites-available/000-default.conf
Update your config to:
<VirtualHost *:80>
ServerAdmin admin@yourdomain.com
DocumentRoot /var/www/vuefront/dist
Alias /frontend /var/www/vuefront/dist
<Directory /var/www/vuefront/dist>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
RewriteEngine On
RewriteBase /frontend
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /frontend/index.html [L]
</Directory>
</VirtualHost>
Save the file (`CTRL + X`, then `Y`, then `Enter`).
### **Restart Apache**
sudo systemctl restart apache2
—
## **3οΈβ£ Ensure `.htaccess` Exists in `dist/`**
Inside your Vue build folder (`/var/www/vuefront/dist`), create an `.htaccess` file:
sudo nano /var/www/vuefront/dist/.htaccess
Paste the following:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /frontend
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Save and exit.
Restart Apache again:
sudo systemctl restart apache2
—
## **4οΈβ£ Clear Browser & Apache Cache**
To ensure old settings are not affecting the app:
– **Clear Browser Cache** (Shift + Refresh)
– **Clear Apache Cache**
sudo systemctl restart apache2
—
## **5οΈβ£ Verify & Test**
β
Open `http://your-ec2-ip/frontend/` β Should load Vue.js β
β
Navigate to `http://your-ec2-ip/frontend/news` β Should work β
β
**Press F5 (refresh on `/frontend/news`)** β Should NOT give a 404 β
—
### **If the 404 Error Still Persists:**
1. Run:
sudo tail -f /var/log/apache2/error.log
Refresh the page and check for errors.
2. Check Vue Router history mode:
– If `createWebHistory(import.meta.env.BASE_URL)` isn't working, try `createWebHashHistory()`
import { createWebHashHistory } from 'vue-router'
– If it works
—
## **1οΈβ£ Check If Apache Is Serving Files Correctly**
First, test whether Apache is correctly serving your Vue app.
– Open: **http://your-ec2-ip/frontend/**
If the homepage **loads**, then Apache is serving static files. β
– Open: **http://your-ec2-ip/frontend/some-random-url**
If it **gives 404**, then Apache isn't redirecting to `index.html`. β
—
## **2οΈβ£ Update Apache VirtualHost Configuration**
If Apache is not redirecting Vue.js routes correctly, modify the Apache config:
### **Edit Apache Configuration**
sudo nano /etc/apache2/sites-available/000-default.conf
Modify it as follows:
<VirtualHost *:80>
ServerAdmin admin@yourdomain.com
DocumentRoot /var/www/vuefront/dist
Alias /frontend /var/www/vuefront/dist
<Directory /var/www/vuefront/dist>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
# Enable Rewrite Engine
RewriteEngine On
RewriteBase /frontend
# Redirect all non-existent files to index.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /frontend/index.html [L]
</Directory>
</VirtualHost>
Save and exit (`CTRL + X`, then `Y`, then `Enter`).
### **Restart Apache**
sudo systemctl restart apache2
—
## **3οΈβ£ Ensure `.htaccess` Exists in `dist/`**
Inside your Vue **build folder** (`/var/www/vuefront/dist`), create or update `.htaccess`:
sudo nano /var/www/vuefront/dist/.htaccess
Paste the following:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /frontend
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Save and restart Apache:
sudo systemctl restart apache2
—
## **4οΈβ£ Check If mod_rewrite Is Enabled**
Make sure `mod_rewrite` is enabled:
sudo a2enmod rewrite
sudo systemctl restart apache2
Then verify:
apachectl -M | grep rewrite
If you see `rewrite_module`, itβs enabled. β
—
## **5οΈβ£ Double-Check Vue Router Configuration**
Your Vue Router is using **`createWebHistory()`**, which requires Apache to **handle history mode**. If the issue persists, switch to `createWebHashHistory()` and rebuild the project.
### **Modify `router.js`**
import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(), // Use hash mode instead of history mode
routes: [
{ path: '/', component: HomeView },
{ path: '/news', component: NewsView },
{ path: '/youtube', component: Youtubeiew },
{ path: '/login', component: LoginView },
{ path: '/register', component: RegisterView },
{ path: '/dashboard', component: DashboardView, meta: { requiresAuth: true } },
{ path: '/profile', component: ProfileView, meta: { requiresAuth: true } },
{ path: '/settings', component: SettingsView, meta: { requiresAuth: true } },
]
});
—
## **6οΈβ£ Rebuild and Deploy the Vue App**
If you changed the router mode, rebuild the Vue app:
npm run build
Then, **copy the `dist/` folder** to `/var/www/vuefront/`.
sudo cp -r dist/* /var/www/vuefront/
Restart Apache:
sudo systemctl restart apache2
—
## **7οΈβ£ Test and Debug**
### β
Test These Cases
| URL | Expected Outcome |
|—-|—————-|
| `http://your-ec2-ip/frontend/` | Vue homepage loads β
|
| `http://your-ec2-ip/frontend/news` | Works normally β
|
| **Refresh on `/frontend/news`** | Works without 404 β
|
—
## **Final Summary**
βοΈ **Updated Apache VirtualHost to redirect unknown paths to `index.html`**
βοΈ **Ensured `.htaccess` properly redirects routes**
βοΈ **Enabled `mod_rewrite` in Apache**
βοΈ **Switched to `createWebHashHistory()` if `createWebHistory()` was causing issues**
βοΈ **Rebuilt and redeployed the Vue app**
π Try this and let me know if the 404 still persists!
—
## **1οΈβ£ Update Your `frontend.conf`**
Modify `/etc/apache2/sites-available/frontend.conf`:
sudo nano /etc/apache2/sites-available/frontend.conf
Paste the following:
<VirtualHost *:80>
ServerAdmin admin@yourdomain.com
DocumentRoot /var/www/vuefront/dist
ServerName yourdomain.com
ServerAlias www.yourdomain.com
<Directory /var/www/vuefront/dist>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
# Enable Rewrite Engine
RewriteEngine On
RewriteBase /
# Redirect all non-existent files to index.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</Directory>
ErrorLog ${APACHE_LOG_DIR}/frontend_error.log
CustomLog ${APACHE_LOG_DIR}/frontend_access.log combined
</VirtualHost>
### **π Key Fixes in This Configuration**
βοΈ **Ensures that unknown URLs go to `index.html`**
βοΈ **Logs errors to `frontend_error.log` for debugging**
βοΈ **Supports `createWebHistory()` in Vue.js**
—
## **2οΈβ£ Enable Your `frontend.conf`**
sudo a2ensite frontend.conf
sudo systemctl restart apache2
—
## **3οΈβ£ Verify That `mod_rewrite` Is Enabled**
sudo a2enmod rewrite
sudo systemctl restart apache2
apachectl -M | grep rewrite
If you see `rewrite_module`, itβs enabled β .
—
## **4οΈβ£ Add `.htaccess` in `dist/`**
In `/var/www/vuefront/dist/.htaccess`:
sudo nano /var/www/vuefront/dist/.htaccess
Paste this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Restart Apache again:
sudo systemctl restart apache2
—
## **5οΈβ£ Clear Browser Cache & Test**
Now, test the following:
β
`http://your-ec2-ip/` β Should load Vue.js app
β
`http://your-ec2-ip/news` β Should work
β
Refresh on `http://your-ec2-ip/news` β Should NOT give 404
—
## **6οΈβ£ Alternative Fix: Use Hash Mode in Vue Router**
If the issue **still persists**, change `createWebHistory()` to `createWebHashHistory()` in `router.js`:
import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(), // Use hash mode
routes: [
{ path: '/', component: HomeView },
{ path: '/news', component: NewsView },
{ path: '/youtube', component: Youtubeiew },
{ path: '/login', component: LoginView },
{ path: '/register', component: RegisterView },
{ path: '/dashboard', component: DashboardView, meta: { requiresAuth: true } },
{ path: '/profile', component: ProfileView, meta: { requiresAuth: true } },
{ path: '/settings', component: SettingsView, meta: { requiresAuth: true } },
]
});
Then **rebuild Vue.js**:
npm run build
And copy `dist/` again:
sudo cp -r dist/* /var/www/vuefront/
—
## **Final Steps**
βοΈ **Check logs for errors:**
sudo tail -f /var/log/apache2/frontend_error.log
βοΈ **If still 404, try accessing**:
π `http://your-ec2-ip/index.html` β If this works, it means Apache isn't rewriting correctly.
π‘ **Let me know what happens, and we can debug further!** π
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
### **β
Solution: Enable Rewrite Rules for Vue.js in Alias**
Modify your Apache configuration and add **rewrite rules** inside the “ block.
—
### **1οΈβ£ Update Your Apache Configuration**
Edit your Apache config file (`frontend.conf` or main site config):
sudo nano /etc/apache2/sites-available/frontend.conf
Modify it to include the rewrite rules:
Alias /frontend /var/www/vuefront/dist
<Directory /var/www/vuefront/dist>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
# Enable Rewrite Engine
RewriteEngine On
RewriteBase /frontend/
# Redirect all non-existent files to index.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /frontend/index.html [L]
</Directory>
**Key Fixes:**
βοΈ **Ensures Vue.js handles routing (prevents 404 on refresh)**
βοΈ **Works with your `/frontend` alias**
—
### **2οΈβ£ Enable `mod_rewrite` & Restart Apache**
sudo a2enmod rewrite
sudo systemctl restart apache2
—
### **3οΈβ£ Add `.htaccess` Inside `dist/`**
If `AllowOverride All` is set, add a `.htaccess` file inside `/var/www/vuefront/dist/`:
sudo nano /var/www/vuefront/dist/.htaccess
Paste this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /frontend/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /frontend/index.html [L]
</IfModule>
Then restart Apache:
sudo systemctl restart apache2
—
### **4οΈβ£ Clear Cache & Test**
1. **Clear browser cache** and **hard refresh** (`Ctrl + Shift + R`).
2. **Try navigating to `/frontend/news` and refresh**.
3. If still 404, check Apache logs:
sudo tail -f /var/log/apache2/error.log
—
### **5οΈβ£ Alternative: Use Hash Mode in Vue Router**
If you **still get 404 errors**, modify your `router.js` to use `createWebHashHistory()` instead:
import { createRouter, createWebHashHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(), // Use hash mode
routes: [
{ path: '/', component: HomeView },
{ path: '/news', component: NewsView },
{ path: '/youtube', component: Youtubeiew },
{ path: '/login', component: LoginView },
{ path: '/register', component: RegisterView },
{ path: '/dashboard', component: DashboardView, meta: { requiresAuth: true } },
{ path: '/profile', component: ProfileView, meta: { requiresAuth: true } },
{ path: '/settings', component: SettingsView, meta: { requiresAuth: true } },
]
});
Then **rebuild Vue.js**:
npm run build
And redeploy:
sudo cp -r dist/* /var/www/vuefront/
—
### **Final Steps**
βοΈ **Test `/frontend` and refresh**
βοΈ **Check if `/frontend/news` refresh works**
βοΈ **If still an issue, check logs**:
sudo tail -f /var/log/apache2/error.log
**Let me know if you still face issues! π**