Home >Backend Development >PHP Tutorial >How to Enforce SSL/HTTPS Using .htaccess and mod_rewrite?
Enforcing SSL/HTTPS with .htaccess and mod_rewrite
To enforce SSL/HTTPS with .htaccess and mod_rewrite, several approaches are available.
Using mod_ssl
Apache's mod_ssl provides the SSLRequireSSL directive, which restricts access unless HTTPS is enabled. By adding this directive to the SSL-enabled virtual host or directories, you can prevent exposure of sensitive data. However, this method does not redirect to HTTPS.
Using mod_rewrite
To redirect to HTTPS, use mod_rewrite in your .htaccess file:
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Alternative Approaches
Additional options for enforcing HTTPS include:
PHP-Based Solution
In cases where .htaccess is disabled, PHP can be used:
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(); } }
The above is the detailed content of How to Enforce SSL/HTTPS Using .htaccess and mod_rewrite?. For more information, please follow other related articles on the PHP Chinese website!