Home >Backend Development >PHP Tutorial >How to Enforce SSL/HTTPS Site-Wide or Page-Specifically Using .htaccess and mod_rewrite?

How to Enforce SSL/HTTPS Site-Wide or Page-Specifically Using .htaccess and mod_rewrite?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 13:30:16827browse

How to Enforce SSL/HTTPS Site-Wide or Page-Specifically Using .htaccess and mod_rewrite?

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:

  • [mod_ssl SSLRequireSSL Directive](https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslrequiresssl)
  • [mod_rewrite Documentation](https://httpd.apache.org/docs/2.4/rewrite/)
  • [Apache HTTP Server Rewriterule](http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html)

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!

Statement:
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