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
Release: 2024-12-15 13:30:16
Original
764 people have browsed it

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

Using mod_rewrite:

  • Add this rewrite rule to your .htaccess:

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    Copy after login

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template