1. 安装OPENSSL

# yum install mod_ssl openssl

通过安装 mod_ssl和openssl,会自动生成 /etc/httpd/conf.d/ssl.conf 配置文件,下文配置会用到! 如果缺失相关配置文件或mod,可以卸载重新安装。

2. 生成一个自签名证书

已有证书可跳至第3步

首先,生成2048位的加密私钥

# openssl genrsa -out server.key 2048

然后,生成证书签名请求(CSR),这里需要填写许多信息,如国家,省市,公司等

# openssl req -new -key server.key -out server.csr

最后,生成类型为X509的自签名证书。有效期设置3650天,即有效期为10年

# openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt

创建证书后,将文件复制到对应的目录。(可自己选择目录,在 /etc/httpd/conf.d/ssl.conf 文件配置对应路径)

# mkdir /etc/certs
# cp server.crt /etc/certs/
# cp server.key /etc/certs/        
# cp server.csr /etc/certs/

3. 配置Apache Web服务器

修改配置文件 /etc/httpd/conf.d/ssl.conf

修改SSLCertificateFile、SSLCertificateKeyFile为对应的证书路径

# vim /etc/httpd/conf.d/ssl.conf

#   Server Certificate:
# Point SSLCertificateFile at a PEM encoded certificate.  If
# the certificate is encrypted, then you will be prompted for a
# pass phrase.  Note that a kill -HUP will prompt again.  A new
# certificate can be generated using the genkey(1) command.

#SSLCertificateFile /etc/pki/tls/certs/localhost.crt
SSLCertificateFile /etc/certs/server.crt


#   Server Private Key:
#   If the key is not combined with the certificate, use this
#   directive to point at the key file.  Keep in mind that if
#   you've both a RSA and a DSA private key you can configure
#   both in parallel (to also allow the use of DSA ciphers, etc.)

#SSLCertificateKeyFile /etc/pki/tls/private/localhost.key
SSLCertificateKeyFile  /etc/certs/server.key

重新启动httpd服务使更改生效

# service httpd restart
//或者
# systemctl restart httpd

Web服务器现在可以使用HTTPS

4. 强制Apache Web服务器始终使用https

在项目根目录下/var/www/public,编辑文件".htaccess",添加如下内容

RewriteEngine on
RewriteBase / 
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.* https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

php的项目.htaccess配置样例如下

<IfModule mod_rewrite.c>
  Options +FollowSymlinks -Multiviews
  RewriteEngine On
  
  RewriteBase / 
  RewriteCond %{SERVER_PORT} !^443$
  RewriteRule ^.* https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
  
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1]
</IfModule>