apache配置ssl证书

1. 安装apache、openssl和mod_ssl

1
$ yum install httpd openssl mod_ssl -y

2. 启动apache服务

1
2
$ systemctl start httpd   # 启动服务
$ systemctl enable httpd # 设置开机启动

3. 检查apache是否启动

1
2
$ systemctl start httpd  # 看到Active: active (running),表示启动成功
$ systemctl is-active httpd #输出active表示启动成功

4. 查看apache服务器网站根目录

1
grep -ri DocumentRoot  /etc/httpd

查看到如下没有打#的项就是网页(文档)根目录了,即/var/www/html

/etc/httpd/conf.d/ssl.conf:#DocumentRoot "/var/www/html"
/etc/httpd/conf/httpd.conf:# DocumentRoot: The directory out of which you will serve your
/etc/httpd/conf/httpd.conf:DocumentRoot "/var/www/html"
/etc/httpd/conf/httpd.conf: # access content that does not live under the DocumentRoot.

5. 域名解析设置

解析域名(如:luoyui.top)到服务器的ip地址上,比如我这里添加了两条解析记录。

1、解析记录为:记录类型为A ,主机记录为为@ ,记录值为144.34.145.10

2、解析记录为:记录类型为A ,主机记录为为www ,记录值为144.34.145.10

6. 配置 SSL 证书以使用 https

一般地,获取 SSL 证书有两种方式:自签名和购买 CA 颁发的 SSL 证书。自签名的证书可能会被浏览器拦截并提示不受信任,因此建议采用比较可靠的商业颁发机构购买(如 Comodo、Symantec 等)或者免费的 Let’s Encrypt 签发的证书。可以使用 certbot 工具来申请得到免费 Let’ s Encrypt SSL 证书。具体操作可参考《通过certbot工具生成ssl证书》。假设这里已经申请得到了 Let’ s Encrypt SSL 证书,下文将介绍如何在 apache 中配置 SSL 证书以使用 https 。

1
2
3
4
5
6
#创建一个目录来表示网站的根目录
mkdir -p /var/www/test
#创建一个html静态文件以待测试
echo "<h1>Hi, Nginx !</h1>" >> /var/www/test/index.html
#编辑 apache web虚拟主机配置文件
vi /etc/httpd/conf.d/vhost.conf

添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<VirtualHost *:80>
DocumentRoot "/var/www/test"
ServerName luoyui.top
ServerAlias www.luoyui.top
<Directory "/var/www/test">
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
RewriteEngine on
RewriteCond %{SERVER_NAME} =luoyui.top [OR]
RewriteCond %{SERVER_NAME} =www.luoyui.top
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

<IfModule mod_ssl.c>
<VirtualHost *:443>
DocumentRoot "/var/www/test"
ServerName luoyui.top
ServerAlias www.luoyui.top
<Directory "/var/www/test">
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/luoyui.top/cert.pem
SSLCertificateKeyFile /etc/letsencrypt/live/luoyui.top/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/luoyui.top/chain.pem
</VirtualHost>
</IfModule>

如果想要访问 luoyui.top 域名地址时自动重定向到 www.luoyui.top 域名地址,只需要修改<VirtualHost>中相关变量的即可,修改如下:

1
2
3
>RewriteEngine on       # url重定向开启
>RewriteCond %{SERVER_PORT} !^443$ # 指定跳转至443端口
>RewriteRule ^/?(.*)$ https://www.%{SERVER_NAME}/$1 [L,R] # 跳转至https://www.域名.com的url

7. 重启apache服务器

1
service httpd restart


----------- 本文结束 -----------




如果你觉得我的文章对你有帮助,你可以打赏我哦~
0%