准备工作

  • 服务器通过 http 可以正常访问
  • 已经准备好 SSL 证书(pem 文件和 key 文件)
  • Nginx 已经安装了 ssl 模块
  • 443 端口已经开放

ssl 模块

查看 Nginx 是否安装了 ssl 模块

进入 Nginx 安装目录下的 sbin 目录内

1
./nginx -V

要注意这里是大写的 V,小写的只显示版本号

[root@sg sbin]# ./nginx -V
nginx version: nginx/1.20.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: –prefix=/www/server/nginx –with-http_ssl_module

如果出现 --with-http_ssl_module,代表安装了

安装教程查看:点我查看

443 端口

查看开放的端口号

1
firewall-cmd --list-port

[root@sg conf]# firewall-cmd –list-port
80/tcp 443/tcp、

修改配置文件

关于 nginx 配置:nginx 配置中文详解

nginx.conf 配置文件的最后就是配置 https 服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# HTTPS server
#
server {
listen 443 ssl;
server_name xx.cn;

ssl_certificate .pem文件路径;
ssl_certificate_key .key文件路径;

ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;

ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;

# location / {
# root html;
# index index.html index.htm;
# }
}

设置 301 重定向

在监听的 80 端口里面设置

return 301 https://$host$request_uri;

301 重定向与 302 跳转的区别

301 重定向是一种永久重定向,而 302 跳转是临时跳转。

在使用域名跳转的情况下,301 重定向比较常用。搜索引擎在抓取新内容的时候,还会把原本的旧网址用重定向之后的新网址代替

302 跳转,可以在登陆用户访问用户中心的时候重定向到登录页面。接着,搜索引擎就会获取新内容,并保留旧的 URL。由于服务器返回的是 302 代码,搜索引擎会认为新的网址只是暂时的

http 跳转到 https

在默认监听的 80 端口的 sever 中返回一个重定向的地址,中间再加上 301 状态码(否则默认为 302)

1
2
3
4
server {
listen 80;
return 301 https://$host$request_uri;
}

关于 $host$request_uri ,可以参考官网:Module ngx_http_core_module

$host

接受请求的服务器名称

$request_uri

完整的原始请求 URI(带参数)

举个例子

比如:http://tieba.baidu.com/f?kw=photoshop&fr=index

$host:tieba.baidu.com

$request_uri:/f?kw=photoshop&fr=index

最后返回的结果就是:https://tieba.baidu.com/f?kw=photoshop&fr=index