0x0. 准备
- Nginx
- 域名证书
0x1. 安装 Nginx
本文使用的是 Nginx 1.18.0,安装过程略。
- 使用官方安装包安装
Nginx 官网:https://nginx.org/en/download.html
- 使用 Docker 部署
Docker Hub - Nginx:https://hub.docker.com/_/nginx
0x2. http 强转 https
1). 使用 return/rewrite
以下是 Nginx 配置
- return 写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 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 写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 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
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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
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
| server { listen 80; listen 443 ssl; server_name your_domain;
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 文件位置
以下是 Nginx 配置
1 2 3 4 5 6 7 8 9 10 11
| 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
,文件内容如下:
1 2 3 4
| <html> <meta http-equiv="refresh" content="0;url=your_https_url"> </html>
|
解释:
your_domain
:你的域名
your_https_url
:你想要强转的 https URL