Angular 路由的 htaccess 重定向 [英] htaccess redirect for Angular routes

查看:27
本文介绍了Angular 路由的 htaccess 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个路由的 Angular 应用程序,例如:

I have an angular application with several routes, such as:

site.com/
site.com/page
site.com/page/4

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

Using angular's html5 routing mode, these resolve correctly when you click links to them from within the application, but of course are 404 errors when you do a hard refresh. To fix this, I've tried implementing a basic htaccess rewrite.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_METHOD} !OPTIONS
RewriteRule ^(.*)$ index.html [L]

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

This works for the angular requests, however when I try to load scripts or make ajax calls within my domain, such as:

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

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

This script doesn't load - it's request is redirected and it tries to load the index.html page as the .htaccess thinks it should reroute the request - not knowing that this file does exist and it should load the file instead of redirect.

有没有什么办法可以让 htaccess 将请求重定向到 index.html(使用视图参数),只有在没有实际文件应该解析到的情况下?

Is there any way I can have the htaccess redirect the request to index.html (with the view parameters) only if there is not an actual file that it should resolve to?

推荐答案

使用如下代码片段:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) /index.html [NC,L]

这将跳到实际资源(如果有),以及所有 AngularJS 路由的 index.html.

This will skip to the actual resource if there is one, and to index.html for all AngularJS routes.

这篇关于Angular 路由的 htaccess 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆