Home > Backend Development > PHP Tutorial > How to Enforce SSL/HTTPS Using .htaccess and mod_rewrite?

How to Enforce SSL/HTTPS Using .htaccess and mod_rewrite?

DDD
Release: 2024-12-30 12:24:17
Original
196 people have browsed it

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]
Copy after login

Alternative Approaches

Additional options for enforcing HTTPS include:

  • Methods outlined in "HTTP-HTTPS (SSL Redirect) with RewriteRule": http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html

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();
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template