i have configure my nginx with these config
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location /apps/ {
try_files $uri $uri/ index.php;
}
my result of npm run build i was rename mv dist apps
the first router path '/' would redirect to /login path
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
scrollBehavior() {
return { x: 0, y: 0 }
},
routes: [
{
path: '/',
name: 'auth-login',
component: () => import('#/views/pages/authentication/Login.vue'),
meta: {
layout: 'full',
resource: 'Auth',
redirectIfLoggedIn: true,
},
},
]
so when i going to www.subdomain.maindomain.id/apps would like redirect into www.subdomain.maindomain.id/apps/login
but when i tried refresh , 404 is appear. ( File not found. )
i have was tried with other
location = /apps/ {
# try_files $uri $uri/ /apps/dist/index.html;
# alias /apps/dist/index.html;
return 301 /apps/dist/index.php;
}
location /apps/dist/ {
try_files $uri $uri/ index.php;
}
location #rewrites {
rewrite ^.*$ /index.html last;
}
still i got 404 on refresh
and this my full config nginx https://gist.github.com/yogithesymbian/b137be9aa2adb87ac7652b9bfbf9394c
if i change my mode to hash
mode: 'hash',
my page can be refresh but have #
I think u need a redirect for '/apps/login' to '/apps' in nginx.
For Vue, there is one page only, which is the root page (rest pages are generated by js). Although you see /apps/login, /apps/login.html or /apps/login.php do not actually exist. In other words, file /apps/dist/login.php(in your case, nginx run:try_files $uri $uri/ index.php; ) is not found. Therefore, it return 404.
Personally, I do not recommend to use history. It is too clumsy for building up the redirect path for these similar case. If you don't want to handle that, use hash mode and utilize routes function in Vue.
Related
How can I create 404 error page with 404 response code in Vue? Here is the route for 404.
{
path: "*",
name: "404",
component: load("404"),
alias: "/404"
}
You won't be able to set the HTTP status code in a Single-Page Application - all the routing is done on the same page in the browser so once the page is loaded no more HTTP status codes will be received.
However, if you try to load a non-existent route by directly typing/copying the URL into the address bar of the browser - then you can use nginX (or whatever server software you are using) to signal 404 HTTP status:
server {
error_page 404 /404.html;
location / {
try_files $uri $uri/ =404;
}
}
But this is not a practical/wise approach - basically, you want every non-existent path to be resolved to /index.html so that your SPA is always loaded and once loaded - it will detect that this route does not exist and will render your 404 component.
So your nginX config should look like this:
server {
...
location / {
try_files $uri /index.html$is_args$args;
}
}
The $is_args variable will add ? if $args is not empty while $args will provide the query parameters (if any).
Your route definition looks ok, except that I don't know your load function does, i.e. how it resolves to a Vue component. But in general your code follows the common approach as described in the Vue router docs. Usually you won't need a name or an alias here since this route is not used explicitly. Just put in a component that shows your "not found" content and you should be good to go:
{
path: "*",
component: PageNotFound
}
Since this is very close to the code you provided, please explain what exactly gives you a problem.
Like IVO GELOV wrote, you have to force this on the server. I came across the issue with Apache (IVO GELOV provides help on nginx).
In the vue router (Vue 3):
const routes = [
{
// Your other routes here
// ...
{
path: '/404',
name: '404',
component: Error404,
},
{
path: '/:pathMatch(.*)*',
beforeEnter() { window.location.href = "/404" },
},
]
With the last route item, all non-matched routes will be redirected to /404. I use beforeEnter to avoid creating a component and window.location.href to get out of the Vue application.
In Apache .htaccess:
<IfModule mod_alias.c>
Redirect 404 /404
</IfModule>
This will add a 404 error code to the /404 url.
Then the /404 route from the vue router config will call the Error404 component that you have to define and import like any other Vue component!
This answer is heavily inspired by:
https://stackoverflow.com/a/62651493/14217548
Despite of multiple posts on the subject I can't find what is going wrong. I been followed this example.
Here is my VueRouter instance.
const router = new VueRouter({
mode: "history",
routes: [
{
path: "/",
component: require("./components/producer-table.vue").default
},
{
path: "/producer/:producerId",
component: require("./components/variable-table.vue").default,
props: true
},
{ path: "*", redirect: "/" }
]
});
If I route to a wrong url programmatically (this.$router.push({path: "/wrong});) I am redirected to http://localhost/.
Everything seems to work fine except that when I set a wrong address in Chrome url bar I get the following message:
Cannot GET /wrong
I would expect http://localhost/wrong to be redirected to http://localhost/. I'm quite new using vue router and I'm must miss something. Any ideas?
This is because your webserver doesn't know GET /wrong should be redirected to the index.html file; from there on, vue-router can take over.
Some examples on how to redirect different web servers;
Apache: htaccess rewrite all to index.html
nginx: Rewrite all requests to index.php with nginx
webpack-dev-server:
/// in your webpack.config
devServer: {
historyApiFallback: {
index: '/'
}
}
Through $router.push({ path:/week/${year}/${month}/${day}/}) I can successfully route/move (not sure about what term to use here) to a different route, with the URL correctly updating.
However once there, if I refresh the browser, the routed component becomes empty (and no console error).
Any idea what's going on here?
Here's my router code:
let router = new Router({
mode: 'history',
routes: [
...
{
path: '/',
redirect: '/home',
meta: {
requiresAuth: true
}
},
{
path: '/week/:year/:month/:day',
component: Home,
meta: {
requiresAuth: true
}
},
...
]
})
You need to configure whichever server that you are using to handle the router as you are using history mode.
I will post the sample configuration for Apache and Nginx since they are most commonly used.
Apache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Nginx
location / {
try_files $uri $uri/ /index.html;
}
Additional information can be found on the official docs.
I am using laravel mix and vuejs for my app and everything works fine.
Now I tried to change the VueRouter to history mode:
const router = new VueRouter({
mode: 'history'
})
On the ngix server, I added the catch all rule:
location / {
try_files $uri $uri/ /index.html;
}
Because of that its still working, when accessing or refreshing top level urls like "/pages" or "/contact".
The only problem is with sublevel urls like /pages/1 or /foo/bar/boo. Clicking on a router link still works, but if I try to refresh the page on /pages/1 or if I try to directly access it (enter /pages/1 in browser) its not working, since the browser tries to access the assets from /pages/js/2.js instead of /js/2.js
Ok, I just found it out - I had to set the public path to an absolute path in my webpack.mix.js file:
mix.webpackConfig({
...
output: {
...
publicPath: "/"
}
});
I have a vue.js application with vue router to render various components. I have a path /home which loads the home component. In the dev environment, I was able to go to the component by giving localhost:8080/home in my address bar and also by setting links using <router-link>. When I deploy the production build to apache server, when I give localhost/home is giving the error
The requested URL /home was not found on this server.
But the links are working and localhost/home is shown in the address bar when we click on the link
Why this happens? How to solve this?
Directly from the Vue router web site.
The default mode for vue-router is hash mode - it uses the URL hash to
simulate a full URL so that the page won't be reloaded when the URL
changes.
To get rid of the hash, we can use the router's history mode, which
leverages the history.pushState API to achieve URL navigation without
a page reload:
const router = new VueRouter({ mode: 'history', routes: [...] })
When using history mode, the URL will look "normal," e.g.
http://oursite.com/user/id. Beautiful!
Here comes a problem, though: Since our app is a single page client
side app, without a proper server configuration, the users will get a
404 error if they access http://oursite.com/user/id directly in their
browser. Now that's ugly.
Not to worry: To fix the issue, all you need to do is add a simple
catch-all fallback route to your server. If the URL doesn't match any
static assets, it should serve the same index.html page that your app
lives in. Beautiful, again!
Apache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
nginx
location / {
try_files $uri $uri/ /index.html;
}
Native Node.js
const http = require('http')
const fs = require('fs')
const httpPort = 80
http.createServer((req, res) => {
fs.readFile('index.htm', 'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.htm" file.')
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})
res.end(content)
})
}).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})
[0] https://router.vuejs.org/en/essentials/history-mode.html
In the router instance, I used history mode which gives a URL without hash(#). I changed the mode form 'history' to the default 'hash' and it solved the problem for me.