Vue.js 404 Error Fix

User
on page refresh vue js url 404 error
Assistant
If you're facing a **404 error on page refresh** in your **Vue.js** application, it's likely because you're using **Vue Router in history mode**. When you refresh the page, the browser directly requests the URL from the server, but since the server doesn't recognize the route, it returns a 404 error.

### **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!

User
standalone vue not using laravel
works well in local but in production on page referesh it give 404 error
Assistant
If your **standalone Vue.js application** works fine locally but gives a **404 error on page refresh in production**, it's because you're using **Vue Router with history mode**. When the page is refreshed, the browser directly requests the URL from the server, but since there's no physical file matching that route, the server returns a 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! πŸš€

User
import { createRouter, createWebHistory } from 'vue-router'
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

Assistant
Your **Vue Router** setup is correctly using **`createWebHistory`**, which removes the `#` from URLs but requires proper server configuration. Since you're facing a **404 error on page refresh in production**, the issue is likely due to missing rewrite rules on your server.

### **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.

User
still 404
Assistant
If you're still getting a **404 error on page refresh**, let's go step by step to diagnose and fix it.

## **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! πŸš€

User
still 404 on page rgeresh
Assistant
If you're still facing a **404 error on page refresh** in your standalone Vue.js app in production, let's debug systematically.

### **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

User
we are using aws ec2
files in vuefront/dist

we have created this
Alias /frontend /var/www/vuefront/dist

Options Indexes FollowSymLinks
AllowOverride All
Require all granted

Assistant
Since you're hosting your **Vue.js** app on **AWS EC2** with **Apache**, and you're using an alias (`Alias /frontend /var/www/vuefront/dist`), you need to ensure that **Vue Router’s history mode (`createWebHistory()`) works correctly**.

## **πŸ” 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! πŸš€

User
still 404
Assistant
If you're still getting a **404 error on page refresh** for your Vue.js app on **AWS EC2 (Apache)**, let's go step by step to debug and fix it.

## **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

User
still not work
Assistant
Since you're still getting a **404 error on page refresh** in your Vue.js app on AWS EC2 with Apache, let's go through a more detailed debugging and fix approach.

## **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!

User
we have created seperatate frontend.conf
Assistant
Since you have a separate `frontend.conf`, let's make sure it is correctly configured for Vue.js with history mode. Here’s what you need to check and update:

## **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!** πŸš€

User
site in Alias /frontend /var/www/vuefront/dist

Options Indexes FollowSymLinks
AllowOverride All
Require all granted

Assistant
Since you're using an alias (`Alias /frontend /var/www/vuefront/dist`), Apache is not automatically rewriting Vue.js routes to `index.html`, which is why you're getting a **404 error on page refresh**.

### **βœ… 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! πŸš€**

Leave a Comment

Your email address will not be published. Required fields are marked *