大家好,Nginx是一个很流行、很强大的代理软件,我们可以借助Nginx,设置http强转https。
0x0. 准备
- Nginx
- 域名证书
0x1. 安装 Nginx
本文使用的是 Nginx 1.18.0,安装过程略。
- 使用官方安装包安装
- 使用 Docker 部署
0x2. http 强转 https
1). 使用 return/rewrite
以下是 Nginx 配置
- return 写法
server {
listen 80;
server_name your_domain;
return ^(.*)$ your_https_url;
# 自定义域名设置
#if ($host = "eq_domain") {
# return ^(.*)$ your_https_url;
#}
access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
解释:
- your_domain:你的域名
- eq_domain:匹配上的域名
- your_https_url:你想要强转的 https URL
- rewrite 写法
server {
listen 80;
server_name your_domain;
return 301 your_https_url;
# 自定义域名设置
#if ($host = "eq_domain") {
# return 301 your_https_url;
#}
access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
解释:
- your_domain:你的域名
- eq_domain:匹配上的域名
- your_https_url:你想要强转的 https URL
2). 使用 497 状态码
以下是 Nginx 配置
- 配置 80
本机 80 端口强转至其他 https URL
server {
listen 80;
server_name your_domain;
access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 497 your_https_url;
}
解释:
- your_domain:你的域名
- your_https_url:你想要强转的 https URL
- 配置 80 和 443
本机 80 端口的 http 强转至 本机 443 端口的 https
server {
listen 80;
listen 443 ssl;
server_name your_domain;
#强制ssl
ssl on;
ssl_certificate your_crt_path.crt;
ssl_certificate_key your_key_path.key;
#缓存有效期
ssl_session_timeout 5m;
#安全链接可选的加密协议
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
#加密算法
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
#使用服务器端的首选算法
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 497 https://$host$uri?$args;
}
解释:
- your_domain:你的域名
- your_crt_path:证书 crt 文件位置
- your_key_path:证书 key 文件位置
3). 利用 meta 的刷新作用
以下是 Nginx 配置
server {
listen 80;
server_name your_domain;
access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
在/usr/share/nginx/html
新建index.html
/index.htm
,文件内容如下:
<html>
<meta http-equiv="refresh" content="0;url=your_https_url">
</html>
解释:
your_domain
:你的域名your_https_url
:你想要强转的 https URL
好了,本期内容到这里就结束了,喜欢这篇文章的朋友可以帮忙点一个免费的赞,这对我很重要,我们下期再见!拜拜