apache上的vue-router,子目录下的SPA,只能通过redirect访问页面

Vue-router on apache, SPA in sub-directory, can only access pages by redirect

所以我在 apache 开发服务器上为客户端设置了一个 Vue 应用程序。我这样做是为了匹配生产环境。该应用程序位于子目录中,我在 vue-router 上设置 'base' 选项以匹配。如果我导航到我的虚拟主机根目录,它会正确重定向,但是通过输入地址导航到同一地址会出现 404。

这是我的路由器代码:

const routes = [
  {path: '/', redirect: '/london' },
  {path: '/:city', component: homeView}
]

const router = new VueRouter ({
  mode: 'history',
  routes,
  base: '/subdir/'
})

我在 'subdir':

中也有相关的 Apaache .htaccess
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.html$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.html [L]
</IfModule>

因此,如果我导航到 "cityapp.local/subdir",它会重定向到 "cityapp.local/subdir/london",但是如果我输入 "cityapp.local/subdir/london",我会得到 apache 404 页面。

如有任何想法或帮助,我们将不胜感激!

编辑:如果我将我的虚拟主机设置为包含子目录并从路由器中删除基本选项,则一切正常。但是,我无法在生产环境中执行此操作,因此我希望此信息能有所帮助。

天哪,昨天和今天花了很长时间寻找解决方案,刚刚找到答案:Vue help forum: Vue webpack project path change

我发现的任何其他人的相关代码:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /subdirectoryName
RewriteRule ^subdirectoryName/index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /subdirectoryName/index.html [L]
</IfModule>

老实说,我昨天尝试过类似的东西。我将 RewriteBase 更改为子目录,但没有更改重写规则!我不擅长 .htaccesss :(

这可能是您的 apache 版本存在错误。

“^$”的重写规则在 2.2.21 和 2.4.2 之间中断 https://bz.apache.org/bugzilla/show_bug.cgi?id=53929

您可以在您的 apache 配置中使用回退资源而不是 mod_rewrite。 它对我有用。

/etc/apache2/apache2.conf

<VirtualHost *:80>
    ServerName YourServerName
    DocumentRoot /var/www/yourApp/dist
    <Directory "/var/www/yourApp/dist">
        FallbackResource /index.html
    </Directory>
</VirtualHost>

我通过在我的站点配置中添加 FallbackResource /index.html 解决了这个问题...

目录在/etc/apache2/sites-enabled/{你的域}.conf

DocumentRoot /var/www/yourApp/dist
<Directory "/var/www/yourApp/dist">
    FallbackResource /index.html
</Directory>