Force SSL/https using .htaccess and mod_rewrite

后端 未结 9 1793
一向
一向 2020-11-22 05:24

How can I force to SSL/https using .htaccess and mod_rewrite page specific in PHP.

9条回答
  •  不知归路
    2020-11-22 05:47

    PHP Solution

    Borrowing directly from Gordon's very comprehensive answer, I note that your question mentions being page-specific in forcing HTTPS/SSL connections.

    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( '' );
        }
      }
    }
    

    Then, as close to the top of these pages which you want to force to connect via PHP, you can require() a centralised file containing this (and any other) custom functions, and then simply run the forceHTTPS() function.

    HTACCESS / mod_rewrite Solution

    I have not implemented this kind of solution personally (I have tended to use the PHP solution, like the one above, for it's simplicity), but the following may be, at least, a good start.

    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]
    

提交回复
热议问题