Nginx配置http跳转到https

现有域名test.com www.test.com配置https
需要将http跳转到https,将test.com跳转到www.test.com
Nginx配置示例如下

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
server {
listen 80;
server_name www.test.com test.com;
rewrite ^(.*)$ https://${server_name}$1 permanent;
}
server {
listen 443;
server_name www.test.com test.com;
if ( $host != 'www.test.com' ) {
rewrite ^/(.*)$ https://www.test.com/$1 permanent;
}



ssl on;
ssl_certificate /data/nginx/cert/cert_www.test.com.crt;
ssl_certificate_key /data/nginx/cert/cert_www.test.com.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;


access_log logs/access_test.log main;
error_log logs/error_test.log error;


location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow_Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

root /data/work/test;
index login.html login.htm;
error_page 405 =200 $uri;
}
}

以上配置访问http://www.test.com https://test.com https://test.com
最终都会跳转到https://www.test.com
也可以将配置一个server
实例如下:

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
server {
listen 80;
listen 443 sssl;
server_name www.test.com test.com;
if ( $host != 'www.test.com' ) {
rewrite ^/(.*)$ https://www.test.com/$1 permanent;
}



#ssl on;
ssl_certificate /data/nginx/cert/cert_www.test.com.crt;
ssl_certificate_key /data/nginx/cert/cert_www.test.com.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;


access_log logs/access_test.log main;
error_log logs/error_test.log error;


location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow_Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

root /data/work/test;
index login.html login.htm;
error_page 405 =200 $uri;
}
}

其中需要将ssl on;注释,将443修改为443 ssl

本文标题:Nginx配置http跳转到https

文章作者:Francis

原始链接:http://www.cnops.com/posts/54491443.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。