htaccess重定向Angular路由

htaccess重定向Angular路由

我有几个路线的角度应用,例如:


site.com/

site.com/page

site.com/page/4

使用angular的html5路由模式,当您从应用程序中单击指向它们的链接时,这些解析正确,但当您进行硬刷新时,当然会出现404错误。为了解决这个问题,我尝试了一个基本的htaccess重写。


RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_METHOD} !OPTIONS

RewriteRule ^(.*)$ index.html [L]

这适用于角度请求,但是当我尝试在我的域中加载脚本或进行ajax调用时,例如:


<script src="/app/programs/script.js"></script>

这个脚本没有加载 - 它的请求被重定向,它试图加载index.html页面,因为.htaccess认为它应该重新路由请求 - 不知道这个文件确实存在,它应该加载文件而不是重定向。


有没有什么方法可以让htaccess将请求重定向到index.html(带有视图参数),只有当它没有应解析的实际文件时?


杨__羊羊
浏览 585回答 3
3回答

喵喵时光机

使用如下代码:RewriteEngine&nbsp;onRewriteCond&nbsp;%{REQUEST_FILENAME}&nbsp;-s&nbsp;[OR]RewriteCond&nbsp;%{REQUEST_FILENAME}&nbsp;-l&nbsp;[OR]RewriteCond&nbsp;%{REQUEST_FILENAME}&nbsp;-dRewriteRule&nbsp;^.*$&nbsp;-&nbsp;[NC,L]RewriteRule&nbsp;^(.*)&nbsp;/index.html&nbsp;[NC,L]如果存在,则跳转到实际资源,并且index.html对于所有AngularJS路由,将跳转到实际资源。

幕布斯7119047

应用程序请求的directive模板文件存在问题,但文件丢失。在某些情况下,它导致应用程序请求多个脚本文件index.html。如果文件不存在,我们应该发送404响应而不是index.html文件。所以我添加简单的正则表达式模式来识别丢失的文件请求。RewriteEngine&nbsp;On#&nbsp;If&nbsp;an&nbsp;existing&nbsp;asset&nbsp;or&nbsp;directory&nbsp;is&nbsp;requested&nbsp;go&nbsp;to&nbsp;it&nbsp;as&nbsp;it&nbsp;isRewriteCond&nbsp;%{DOCUMENT_ROOT}%{REQUEST_URI}&nbsp;-f&nbsp;[OR]RewriteCond&nbsp;%{DOCUMENT_ROOT}%{REQUEST_URI}&nbsp;-dRewriteRule&nbsp;^&nbsp;-&nbsp;[L]#&nbsp;If&nbsp;the&nbsp;requested&nbsp;pattern&nbsp;is&nbsp;file&nbsp;and&nbsp;file&nbsp;doesn't&nbsp;exist,&nbsp;send&nbsp;404RewriteCond&nbsp;%{REQUEST_URI}&nbsp;^(\/[a-z_\-\s0-9\.]+)+\.[a-zA-Z]{2,4}$RewriteRule&nbsp;^&nbsp;-&nbsp;[L,R=404]#&nbsp;otherwise&nbsp;use&nbsp;history&nbsp;routerRewriteRule&nbsp;^&nbsp;/index.html
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS