web.config 파일을 사용하여 HTTPS를 강제 실행하는 방법
나는 이것에 대한 해결책을 찾으려고 Google과 StackOverflow를 검색했지만 모두 ASP.NET 등과 관련이있는 것 같습니다.
일반적으로 서버에서 Linux를 실행하지만이 클라이언트 하나에 IIS 7.5 (및 Plesk 10)가있는 Windows를 사용하고 있습니다. 이것이 IIS와 web.config 파일에 약간 익숙하지 않은 이유 입니다. 에서 .htaccess
파일 당신은 프로토콜이 따라 HTTPS 및 리디렉션 여부를 감지하는 재 작성 조건을 사용할 수 있습니다. web.config 파일을 사용하거나 심지어 설치 한 ' URL Rewrite '모듈을 사용하여이를 달성 하는 간단한 방법 이 있습니까?
ASP.NET에 대한 경험 이 없으므로 솔루션에 관련된 경우 구현 방법에 대한 명확한 단계를 포함하십시오.
PHP가 아닌 web.config 로이 작업을 수행하는 이유 는 사이트 내의 모든 자산에 HTTPS를 강제 적용하기 때문입니다.
URL 재 작성 모듈, 바람직하게는 v2가 필요합니다 (v1이 설치되어 있지 않으므로 작동한다고 보장 할 수는 없지만).
다음은 그러한 web.config의 예입니다. 301 영구 리디렉션을 사용하여 모든 리소스에 대해 HTTPS를 강제 적용합니다.
<?xml version="1.0" encoding="UTF-8"?>
<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>
PS 이 특정 솔루션은 ASP.NET/PHP 또는 다른 기술과 관련이 없습니다. URL 재 작성 모듈 만 사용하기 때문입니다. 요청이 코드가있는 지점에 도달하기 전에 초기 / 낮은 수준 중 하나로 처리됩니다. 처형된다.
ASP.NET MVC를 사용하는 경우 RequireHttpsAttribute 를 사용하여 모든 응답을 HTTPS로 만들 수 있습니다.
GlobalFilters.Filters.Add(new RequireHttpsAttribute());
사이트를 보호하기 위해 수행 할 수있는 다른 작업 :
위조 방지 토큰이 SSL / TLS를 사용하도록합니다.
AntiForgeryConfig.RequireSsl = true;
Web.config 파일을 변경하여 쿠키가 기본적으로 HTTPS를 요구하도록 요구 :
<system.web> <httpCookies httpOnlyCookies="true" requireSSL="true" /> </system.web>
사용 NWebSec.Owin 사이트를 통해 엄격한 전송 보안 (HSTS)를 활성화하기 위해 다음 코드 줄을 NuGet 패키지를 추가합니다. 아래에 사전로드 지시문을 추가하고 사이트를 HSTS 사전로드 사이트에 제출하십시오 . 여기 와 여기에 더 많은 정보가 있습니다 . OWIN을 사용하지 않는 경우 NWebSec 사이트 에서 읽을 수있는 Web.config 메소드가 있습니다 .
// app is your OWIN IAppBuilder app in Startup.cs app.UseHsts(options => options.MaxAge(days: 720).Preload());
Use the NWebSec.Owin NuGet package and add the following line of code to enable Public Key Pinning (HPKP) across the site. More information here and here.
// app is your OWIN IAppBuilder app in Startup.cs app.UseHpkp(options => options .Sha256Pins( "Base64 encoded SHA-256 hash of your first certificate e.g. cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=", "Base64 encoded SHA-256 hash of your second backup certificate e.g. M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE=") .MaxAge(days: 30));
Include the https scheme in any URL's used. Content Security Policy (CSP) HTTP header and Subresource Integrity (SRI) do not play nice when you imit the scheme in some browsers. It is better to be explicit about HTTPS. e.g.
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.4/bootstrap.min.js"> </script>
Use the ASP.NET MVC Boilerplate Visual Studio project template to generate a project with all of this and much more built in. You can also view the code on GitHub.
To augment LazyOne's answer, here is an annotated version of the answer.
<rewrite>
<rules>
<clear />
<rule name="Redirect all requests to https" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action
type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}"
redirectType="Permanent" appendQueryString="false" />
</rule>
</rules>
</rewrite>
Clear all the other rules that might already been defined on this server. Create a new rule, that we will name "Redirect all requests to https". After processing this rule, do not process any more rules! Match all incoming URLs. Then check whether all of these other conditions are true: HTTPS is turned OFF. Well, that's only one condition (but make sure it's true). If it is, send a 301 Permanent redirect back to the client at http://www.foobar.com/whatever?else=the#url-contains
. Don't add the query string at the end of that, because it would duplicate the query string!
This is what the properties, attributes, and some of the values mean.
- clear removes all server rules that we might otherwise inherit.
- rule defines a rule.
- name an arbitrary (though unique) name for the rule.
- stopProcessing whether to forward the request immediately to the IIS request pipeline or first to process additional rules.
- match when to run this rule.
- url a pattern against which to evaluate the URL
- conditions additional conditions about when to run this rule; conditions are processed only if there is first a match.
- logicalGrouping whether all the conditions must be true (
MatchAll
) or any of the conditions must be true (MatchAny
); similar to AND vs OR.
- logicalGrouping whether all the conditions must be true (
- add adds a condition that must be met.
- input the input that a condition is evaluating; input can be server variables.
- pattern the standard against which to evaluate the input.
- ignoreCase whether capitalization matters or not.
- action what to do if the
match
and itsconditions
are all true.- type can generally be
redirect
(client-side) orrewrite
(server-side). - url what to produce as a result of this rule; in this case, concatenate
https://
with two server variables. - redirectType what HTTP redirect to use; this one is a 301 Permanent.
- appendQueryString whether to add the query string at the end of the resultant
url
or not; in this case, we are setting it to false, because the{REQUEST_URI}
already includes it.
- type can generally be
The server variables are
{HTTPS}
which is eitherOFF
orON
.{HTTP_HOST}
iswww.mysite.com
, and{REQUEST_URI}
includes the rest of the URI, e.g./home?key=value
- the browser handles the
#fragment
(see comment from LazyOne).
- the browser handles the
See also: https://www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference
The accepted answer did not work for me. I followed the steps on this blog.
A key point that was missing for me was that I needed to download and install the URL Rewrite Tool for IIS. I found it here. The result was the following.
<rewrite>
<rules>
<remove name="Http to Https" />
<rule name="Http to Https" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<serverVariables />
<action type="Redirect" url="https://{HTTPS_HOST}{REQUEST_URI}" />
</rule>
</rules>
</rewrite>
In .Net Core, follow the instructions at https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl
In your startup.cs add the following:
// Requires using Microsoft.AspNetCore.Mvc;
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});`enter code here`
To redirect Http to Https, add the following in the startup.cs
// Requires using Microsoft.AspNetCore.Rewrite;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var options = new RewriteOptions()
.AddRedirectToHttps();
app.UseRewriter(options);
The excellent NWebsec library can upgrade your requests from HTTP to HTTPS using its upgrade-insecure-requests
tag within the Web.config
:
<nwebsec>
<httpHeaderSecurityModule>
<securityHttpHeaders>
<content-Security-Policy enabled="true">
<upgrade-insecure-requests enabled="true" />
</content-Security-Policy>
</securityHttpHeaders>
</httpHeaderSecurityModule>
</nwebsec>
I was not allowed to install URL Rewrite in my environment, so, I found another path.
Adding this to my web.config added the error rewrite and worked on IIS 7.5:
<system.webServer>
<httpErrors errorMode="Custom" defaultResponseMode="File" defaultPath="C:\WebSites\yoursite\" >
<remove statusCode="403" subStatusCode="4" />
<error statusCode="403" subStatusCode="4" responseMode="File" path="redirectToHttps.html" />
</httpErrors>
Then, following the advice here: https://www.sslshopper.com/iis7-redirect-http-to-https.html
I created the html file that does the redirect (redirectToHttps.html):
<html>
<head><title>Redirecting...</title></head>
<script language="JavaScript">
function redirectHttpToHttps()
{
var httpURL= window.location.hostname + window.location.pathname + window.location.search;
var httpsURL= "https://" + httpURL;
window.location = httpsURL;
}
redirectHttpToHttps();
</script>
<body>
</body>
</html>
I hope someone finds this useful as I could not find all of the pieces in one place anywhere else.
A simple way is to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.
</configuration>
</system.webServer>
<httpErrors>
<clear/>
<!--redirect if connected without SSL-->
<error statusCode="403" subStatusCode="4" path="errors\403.4_requiressl.html" responseMode="File"/>
</httpErrors>
</system.webServer>
</configuration>
참고URL : https://stackoverflow.com/questions/9823010/how-to-force-https-using-a-web-config-file
'Programing' 카테고리의 다른 글
String, StringBuffer 및 StringBuilder (0) | 2020.05.06 |
---|---|
gradle 의존성이 새로운 버전인지 확인하는 방법 (0) | 2020.05.06 |
git difftool 및 mergetool로 Meld 설정 및 사용 (0) | 2020.05.06 |
x == (x = y)가 (x = y) == x와 다른 이유는 무엇입니까? (0) | 2020.05.06 |
Bash에서 공백을 마침표로 교체 (0) | 2020.05.06 |