0%

Nginx强制Http跳转到Https访问

本文分为两种情况:

  1. http://jaceding.github.com/跳转https://jaceding.github.com/
  2. http://jaceding.github.com:18182/跳转https://jaceding.github.com:18182/

第一种情况

通过监听80端口,然后重定向到Https(默认443端口)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server {
listen 80;
server_name jaceding.github.com;
return 301 https://$server_name$request_uri;
}

server {
listen 443 ssl http2;
server_name jaceding.github.com;
ssl_protocols TLSv1.3 TLSv1.2;
ssl_ciphers EECDH:+CHACHA20:+aRSA:+AES256:!NULL:!ARIA:!CAMELLIA:!SHA:!MD5;
server_tokens off;

access_log /var/log/nginx/page_access main;
error_log /var/log/nginx/page_error;
ssl_certificate /usr/cert/wanxin/wanxinwangluo.com.cer;
ssl_certificate_key /usr/cert/wanxin/wanxinwangluo.com.key;

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

第二种情况

当网站只允许https访问时,用http访问时nginx会报出497错误码。

通过error_page命令将497状态码的链接重定向到https://jaceding.github.com:18182/这个域名上

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
32
33
34
35
36
37
38
39
40
upstream libreSpeed {
server 10.86.52.77:80;
server 10.86.122.208:80;
keepalive 64;
}

server {
listen 18182 ssl http2;
server_name jaceding.github.com;
ssl_protocols TLSv1.3 TLSv1.2;
ssl_ciphers EECDH:+CHACHA20:+aRSA:+AES256:!NULL:!ARIA:!CAMELLIA:!SHA:!MD5;
server_tokens off;

access_log /var/log/nginx/libreSpeed_access main;
error_log /var/log/nginx/libreSpeed_error;
ssl_certificate /usr/cert/wanxin/wanxinwangluo.com.cer;
ssl_certificate_key /usr/cert/wanxin/wanxinwangluo.com.key;

error_page 497 https://$host:$server_port$uri$is_args$args;

location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
add_header Cache-Control no-cache;
add_header X-XSS-Protection "1;mode=block";
add_header x-frame-options SAMEORIGIN;
proxy_hide_header X-Powered-By;
proxy_hide_header "cache-control";
proxy_hide_header Expires;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header Host $http_host;
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_pass http://libreSpeed;
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!