Programing

.htaccess 및 mod_rewrite를 사용하여 SSL / https를 강제 실행

lottogame 2020. 4. 18. 09:28
반응형

.htaccess 및 mod_rewrite를 사용하여 SSL / https를 강제 실행


PHP에서 .htaccess 및 mod_rewrite 페이지를 사용하여 SSL / https를 강제로 설정하는 방법


Apache의 경우 다음을 사용 mod_ssl하여 SSL을 강제 실행할 수 있습니다 SSLRequireSSL Directive.

이 지시문은 현재 연결에 대해 SSL을 통한 HTTP (즉, HTTPS)가 활성화되어 있지 않으면 액세스를 금지합니다. 이는 SSL 사용 가상 호스트 또는 디렉토리 내에서 보호해야 할 항목을 노출시키는 구성 오류를 방지하는 데 매우 유용합니다. 이 지시문이 있으면 SSL을 사용하지 않는 모든 요청이 거부됩니다.

그래도 https로 리디렉션하지 않습니다. 리디렉션하려면 mod_rewrite.htaccess 파일에서 다음을 시도 하십시오.

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

또는에 주어진 다양한 접근 중 하나

공급자가 .htaccess를 비활성화 한 경우 PHP 내 에서이 문제를 해결할 수 있습니다 (요청한 이후에는 가능하지 않지만 어쨌든)

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    if(!headers_sent()) {
        header("Status: 301 Moved Permanently");
        header(sprintf(
            'Location: https://%s%s',
            $_SERVER['HTTP_HOST'],
            $_SERVER['REQUEST_URI']
        ));
        exit();
    }
}

mod_rewrite프록시 서버와 프록시되지 않은 서버 모두에서 잘 작동 하는 솔루션을 찾았습니다 .

당신이 사용하는 경우 CloudFlare, AWS 탄성로드 밸런싱, Heroku가, OpenShift 또는 기타 클라우드 / PaaS를 솔루션을 당신이 발생하는 리디렉션 루프 정상 HTTPS 리디렉션과를 대신 다음 코드를 사용해보십시오.

RewriteEngine On

# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on

# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

PHP 솔루션

Gordon의 매우 포괄적 인 답변에서 직접 차용 한 귀하의 질문에 HTTPS / SSL 연결을 강제 할 때 페이지 별 내용이 언급되어 있습니다.

function forceHTTPS(){
  $httpsURL = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
  if( count( $_POST )>0 )
    die( 'Page should be accessed with HTTPS, but a POST Submission has been sent here. Adjust the form to point to '.$httpsURL );
  if( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS']!=='on' ){
    if( !headers_sent() ){
      header( "Status: 301 Moved Permanently" );
      header( "Location: $httpsURL" );
      exit();
    }else{
      die( '<script type="javascript">document.location.href="'.$httpsURL.'";</script>' );
    }
  }
}

그런 다음 PHP를 통해 강제로 연결하려는 페이지 상단에 require()가까워이 (및 기타) 사용자 정의 함수를 포함하는 중앙 집중식 파일을 만든 다음 간단히 forceHTTPS()함수 를 실행할 수 있습니다.

HTACCESS / mod_rewrite 솔루션

나는 이런 종류의 솔루션을 개인적으로 구현하지 않았지만 (단순하기 위해 위의 것과 같은 PHP 솔루션을 사용하는 경향이 있지만) 다음은 적어도 좋은 시작일 수 있습니다.

RewriteEngine on

# Check for POST Submission
RewriteCond %{REQUEST_METHOD} !^POST$

# Forcing HTTPS
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{SERVER_PORT} 80
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_secure [OR]
RewriteCond %{REQUEST_URI} ^something_else_secure
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

# Forcing HTTP
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{SERVER_PORT} 443
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_public [OR]
RewriteCond %{REQUEST_URI} ^something_else_public
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

모드 재 작성 기반 솔루션 :

htaccess에서 다음 코드를 사용하면 모든 http 요청이 https로 자동 전달됩니다.

RewriteEngine on

RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]

이것은 당신의 리디렉션 www가 아닌를 하고 www가 에서 http 요청 www가 HTTPS의 버전.

다른 솔루션 (Apache 2.4 *)

RewriteEngine on

RewriteCond %{REQUEST_SCHEME}::%{HTTP_HOST} ^http::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]

2.4 이후로 % {REQUEST_SCHEME} 변수가 mod-rewrite에 추가되었으므로 아파치 하위 버전에서는 작동하지 않습니다.


디렉토리 깊이에서 여러 .htaccess 파일을 사용할 때 Apache 에 최악의 상속 규칙 이 있음을 지적하고 싶습니다 . 두 가지 주요 함정 :

  • 가장 깊은 .htaccess 파일에 포함 된 규칙 만 기본적으로 수행됩니다. RewriteOptions InheritDownBefore이를 변경 하려면 지시문 (또는 유사한)을 지정해야합니다 . (질문 참조)
  • 패턴은 주어진 규칙에 따라 .htaccess 파일을 포함하는 상위 디렉토리가 아닌 서브 디렉토리에 상대적인 파일 경로에 적용됩니다. (토론 참조)

이는 하위 디렉토리에서 다른 .htaccess 파일을 사용하는 경우 Apache Wiki 의 제안 된 글로벌 솔루션 작동 하지 않음을 의미합니다 . 나는 다음과 같은 수정 된 버전을 썼다.

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteOptions InheritDownBefore
# This prevents the rule from being overrided by .htaccess files in subdirectories.

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [QSA,R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/

이 코드는 나를 위해 작동

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:X-HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

간단하고 쉽게 다음을 추가하십시오.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

다른 답변들 중 어느 것도 나를 위해 일하지 않았습니다. 내 설정은 클래식 ELB가있는 AWS Beanstalk의 PHP 앱입니다. .htaccess 접근 방식이 작동하지 않으므로 아파치 httpd.conf 파일에 리디렉션 규칙을 적용해야했습니다. 예 : (AWS 문서에서) :

Apache 서버 : 가상 호스트 파일 방법 (권장)

  1. Apache 구성 파일을여십시오. 가능한 위치는 /etc/httpd/conf/httpd.conf(Apache 2 / httpd), / etc / apache2 / sites-enabled / (Apache 2.4) 또는 /etc/apache2/apache2.conf(Ubuntu의 Apache)입니다.

  2. 다음과 유사한 구성 파일의 VirtualHost 섹션에 다시 쓰기 규칙을 추가하십시오.

    RewriteEngine On RewriteCond % {HTTP : X-Forwarded-Proto} = http RewriteRule. * https : // % {HTTP : Host} % {REQUEST_URI} [L, R = 영구적]

  3. Apache 구성 파일을 저장하십시오.

  4. 아파치 다시 시작

여기를 참조하십시오 : https://www.youtube.com/watch?v=hvqZV_50GlQ

https://aws.amazon.com/premiumsupport/knowledge-center/redirect-http-https-elb/


간단한 것 :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.example\.com)(:80)? [NC]
RewriteRule ^(.*) https://example.com/$1 [R=301,L]
order deny,allow

URL을 example.com으로 바꾸십시오


Apache .htaccess로 SSL을 강제 실행하기 위해 사용할 수 있습니다

SSLOptions +StrictRequire
SSLRequireSSL

위의 답변을 리디렉션하면 정확합니다.


이 코드를 사용하면 다음과 같은 모든 버전의 URL에서 작동합니다.

  • website.com
  • www.website.com
  • http://website.com
  • http://www.website.com

    RewriteCond %{HTTPS} off
    RewriteCond %{HTTPS_HOST} !^www.website.com$ [NC]
    RewriteRule ^(.*)$ https://www.website.com/$1 [L,R=301]
    

참고 URL : https://stackoverflow.com/questions/4398951/force-ssl-https-using-htaccess-and-mod-rewrite

반응형