HTML5 모드에서 AngularJS 애플리케이션을 URL 재 작성을 위해 IIS를 구성하려면 어떻게해야합니까?
나는이 AngularJS와 종자 프로젝트를 내가 추가 한
$locationProvider.html5Mode(true).hashPrefix('!');
app.js 파일에. 모든 요청을 라우팅하도록 IIS 7을 구성하고 싶습니다.
http://localhost/app/index.html
그래서 이것은 나를 위해 작동합니다. 어떻게해야합니까?
최신 정보:
방금 IIS URL Rewrite 모듈을 발견, 다운로드 및 설치했습니다. 이것이 목표를 달성하는 것이 쉽고 분명해지기를 바랍니다.
업데이트 2 :
이것이 내가 달성하려는 것을 요약 한 것 같습니다 ( AngularJS Developer documentation 에서 가져옴 ).
이 모드를 사용하려면 서버 측에서 URL을 다시 작성해야합니다. 기본적으로 모든 링크를 응용 프로그램의 진입 점으로 다시 작성해야합니다 (예 : index.html)
업데이트 3 :
나는 여전히이 문제를 해결하고 있으며 다음과 같은 특정 URL을 리디렉션하지 않아야합니다 (규칙을 다시 작성해야 함).
http://localhost/app/lib/angular/angular.js
http://localhost/app/partials/partial1.html
따라서 css, js, lib 또는 partials 디렉토리에있는 항목은 경로 재 지정되지 않습니다. 그 밖의 모든 것은 app / index.html로 리디렉션해야합니다.
누구나 단일 파일마다 규칙을 추가하지 않고도 쉽게 달성하는 방법을 알고 있습니까?
업데이트 4 :
IIS URL 다시 쓰기 모듈에 2 개의 인바운드 규칙이 정의되어 있습니다. 첫 번째 규칙은 다음과 같습니다.
두 번째 규칙은 다음과 같습니다.
Now when I navigate to localhost/app/view1 it loads the page, however the supporting files (the ones in the css, js, lib and partials directories) are also being rewritten to the app/index.html page - so everything is coming back as the index.html page no matter what URL is used. I guess this means my first rule, that is supposed to prevent these URLs from being processed by the second rule, isn't working.. any ideas? ...anyone? ...I feel so alone... :-(
I write out a rule in web.config after $locationProvider.html5Mode(true)
is set in app.js
.
Hope, helps someone out.
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
In my index.html I added this to <head>
<base href="/">
Don't forget to install IIS URL Rewrite on server.
Also if you use Web API and IIS, this will work if your API is at www.yourdomain.com/api
because of the third input (third line of condition).
The IIS inbound rules as shown in the question DO work. I had to clear the browser cache and add the following line in the top of my <head>
section of the index.html page:
<base href="/myApplication/app/" />
This is because I have more than one application in localhost and so requests to other partials were being taken to localhost/app/view1
instead of localhost/myApplication/app/view1
Hopefully this helps someone!
The issue with only having these two conditions:
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
is that they work only as long as the {REQUEST_FILENAME}
exists physically on disk. This means that there can be scenarios where a request for an incorrectly named partial view would return the root page instead of a 404 which would cause angular to be loaded twice (and in certain scenarios it can cause a nasty infinite loop).
Thus, some safe "fallback" rules would be recommended to avoid these hard to troubleshoot issues:
<add input="{REQUEST_FILENAME}" pattern="(.*?)\.html$" negate="true" />
<add input="{REQUEST_FILENAME}" pattern="(.*?)\.js$" negate="true" />
<add input="{REQUEST_FILENAME}" pattern="(.*?)\.css$" negate="true" />
or a condition that matches any file ending:
<conditions>
<!-- ... -->
<add input="{REQUEST_FILENAME}" pattern=".*\.[\d\w]+$" negate="true" />
</conditions>
In my case I kept getting a 403.14 after I had setup the correct rewrite rules. It turns out that I had a directory that was the same name as one of my URL routes. Once I removed the IsDirectory rewrite rule my routes worked correctly. Is there a case where removing the directory negation may cause problems? I can't think of any in my case. The only case I can think of is if you can browse a directory with your app.
<rule name="fixhtml5mode" stopProcessing="true">
<match url=".*"/>
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
The easiest way I found is just to redirect the requests that trigger 404 to the client. This is done by adding an hashtag even when $locationProvider.html5Mode(true)
is set.
This trick works for environments with more Web Application on the same Web Site and requiring URL integrity constraints (E.G. external authentication). Here is step by step how to do
index.html
Set the <base>
element properly
<base href="@(Request.ApplicationPath + "/")">
web.config
First redirect 404 to a custom page, for example "Home/Error"
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Home/Error" />
</customErrors>
</system.web>
Home controller
Implement a simple ActionResult
to "translate" input in a clientside route.
public ActionResult Error(string aspxerrorpath) {
return this.Redirect("~/#/" + aspxerrorpath);
}
This is the simplest way.
It is possible (advisable?) to enhance the Error function with some improved logic to redirect 404 to client only when url is valid and let the 404 trigger normally when nothing will be found on client. Let's say you have these angular routes
.when("/", {
templateUrl: "Base/Home",
controller: "controllerHome"
})
.when("/New", {
templateUrl: "Base/New",
controller: "controllerNew"
})
.when("/Show/:title", {
templateUrl: "Base/Show",
controller: "controllerShow"
})
It makes sense to redirect URL to client only when it start with "/New" or "/Show/"
public ActionResult Error(string aspxerrorpath) {
// get clientside route path
string clientPath = aspxerrorpath.Substring(Request.ApplicationPath.Length);
// create a set of valid clientside path
string[] validPaths = { "/New", "/Show/" };
// check if clientPath is valid and redirect properly
foreach (string validPath in validPaths) {
if (clientPath.StartsWith(validPath)) {
return this.Redirect("~/#/" + clientPath);
}
}
return new HttpNotFoundResult();
}
This is just an example of improved logic, of course every web application has different needs
I've been trying to deploy a simple Angular 7 application, to an Azure Web App. Everything worked fine, until the point where you refreshed the page. Doing so, was presenting me with an 500 error - moved content. I've read both on the Angular docs and in around a good few forums, that I need to add a web.config file to my deployed solution and make sure the rewrite rule fallback to the index.html file. After hours of frustration and trial and error tests, I've found the error was quite simple: adding a tag around my file markup.
'IT story' 카테고리의 다른 글
PDO 준비 단일 쿼리에 여러 행을 삽입합니다 (0) | 2020.06.25 |
---|---|
크롬 개발자 도구에서 사람이 읽을 수있는 자바 스크립트 (0) | 2020.06.25 |
신경망에서 학습, 검증 및 테스트 세트의 차이점은 무엇입니까? (0) | 2020.06.25 |
존재하지 않는 경우 새 TMUX 세션을 만드는 방법 (0) | 2020.06.25 |
왜 작업을 사용 하는가 (0) | 2020.06.25 |