Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the # hash from URL when using Vue.js in Laravel Homestead

I have a Laravel 5.2 setup running in Homestead and using Vue.js router to build an SPA. I'm trying to completely remove the #hash from the URL which I know can be done, but I keep getting errors:

I've added rewrite ^(.+)$ /index.html last; to my vhosts file in Homestead:

server {

    listen 80;
    listen 443 ssl;
    server_name app.myproject.dev;
    root "/home/vagrant/Code/vibecast/app.myproject.com/public";

    rewrite ^(.+)$ /index.html last;

    index index.html index.htm index.php;

    charset utf-8;

    ...

}

When I restart and open a page I get a 500 Internal Server Error.

Is there anything I need added to routes in Laravel?

var router = new VueRouter({
    hashbang: false,
    history: true,
    linkActiveClass: "active"
})

I can get it working without the #hash (or the modified hosts file) when navigating around, but fails when I reload a page.

like image 965
Jack Barham Avatar asked Jan 27 '16 15:01

Jack Barham


1 Answers

You can make Vue Router and Laravel Router work together nicely by making the following changes:

At the end of your routes/web.php add the next lines:

Route::get('{path}', function() {
  return view('your-vuejs-main-blade');
})->where('path', '.*');

You need to add this at the end of file because you need to preserve the previously declared laravel routes in order to work properly and not be overwritten by the 404 page or vue-router's paths.

In your Vue router's config use the following:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

let router = new Router({
    mode: 'history', //removes # (hashtag) from url
    base: '/',
    fallback: true, //router should fallback to hash (#) mode when the browser does not support history.pushState
    routes: [
        { path: '*', require('../components/pages/NotFound.vue') },
        //... + all your other paths here
    ]
})
export default router

However, when navigating between laravel and vue-router, you need to keep in mind that leaving vue-router's page to a laravel page you must use a window.location.href code, an <a> tag or some sort of programmatic navigation in order to fully exit Vue-router's instance.

Tested this with Laravel 5.5.23, Vue 2.5.9, Vue-Router 3.0.1

like image 183
aki Avatar answered Oct 12 '22 23:10

aki