Skip to content

Apache 强制 HTTPS

配置方法

1. 使用.htaccess 文件配置

在网站根目录创建或编辑.htaccess 文件,添加以下内容:

apache
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

2. 使用虚拟主机配置

在 Apache 的虚拟主机配置文件中添加重定向规则:

apache
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

注意事项

  1. 确保 mod_rewrite 模块已启用

    • 检查 httpd.conf 文件中是否加载了 mod_rewrite 模块
    • 如果未加载,取消注释 LoadModule 行并重启 Apache
  2. 检查目录权限

    • 确保.htaccess 文件所在目录允许重写规则

    • 在虚拟主机配置中添加:

      apache
      <Directory /path/to/your/website>
          AllowOverride All
      </Directory>
  3. 常见问题排查

    • 检查 Apache 错误日志
    • 确认 SSL 证书配置正确
    • 验证 443 端口是否开放

SSL 证书帮助中心