我在IIS中托管了一个角度应用程序。为了将所有请求重定向到应用程序的根目录并允许角度路由处理不同的路由,我添加了一个带有URL重写规则的web.config文件,如下所示:
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Angular Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
工作正常。但是,我现在需要强制应用程序从HTTP重定向到HTTPS。为此,我可以添加新规则,如以下帖子所示:Angular 2 - always redirect to https:// instead of using http://
强制使用HTTPS的规则:
<configuration>
<system.webServer>
<rewrite>
<rules>
<clear />
<rule name="Redirect to https" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
此规则也有效,但它会将我的重定向分解为之前定义的根规则。那么有没有人知道如何将这两个规则混合在一起或者我可以通过哪种方式实现这两个目的呢?
答案 0 :(得分:9)
作为替代解决方案,我最终直接在角度项目中的主控制器上强制执行https,如下所示。 (张贴在案例中对其他人有用)
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { environment } from '../environments/environment';
@Component({
selector: 'vp-app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'vp-app';
location: Location;
ngOnInit() {
if (environment.production) {
if (location.protocol === 'http:') {
window.location.href = location.href.replace('http', 'https');
}
}
}
}
答案 1 :(得分:4)
重定向到HTTPS和重定向到root
仍在寻找web.config解决方案的人,将您现有的web.config文件代码替换为以下代码:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<!--START REDIRECT TO HTTPS-->
<rule name="Redirect to https" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
</rule>
<!--END REDIRECT TO HTTPS-->
<!--START REDIRECT TO ROOT-->
<rule name="AngularJS" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
<!--END REDIRECT TO ROOT-->
</rules>
</rewrite>
</system.webServer>
</configuration>
注意: 对于IIS 6,您可能需要安装URL Rewrite扩展名才能使其正常工作。
您可以在以下网址找到URL重写扩展名:https://www.iis.net/downloads/microsoft/url-rewrite