How to Enforce SSL/HTTPS Site-Wide or Page-Specifically Using .htaccess and mod_rewrite
To implement SSL/HTTPS enforcement in PHP using .htaccess and mod_rewrite, consider the following approaches:
Site-Wide Enforcement
Using mod_ssl:
Include the following directive in your .htaccess file:
SSLRequireSSL
Using mod_rewrite:
Add this rewrite rule to your .htaccess:
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Page-Specific Enforcement in PHP
If .htaccess is disabled on your server, you can enforce SSL/HTTPS from within 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(); } }
Additional Resources
Refer to the following resources for further information:
The above is the detailed content of How to Enforce SSL/HTTPS Site-Wide or Page-Specifically Using .htaccess and mod_rewrite?. For more information, please follow other related articles on the PHP Chinese website!