如何强制Nginx将全站转向WWW和HTTPS

今天我们来看一下,如何强制Nginx将全站转向WWW和HTTPS,当然了,我们的想法还是非常好的,但是很多时候网站建设受到实际条件的限制,不一定能够实现,所以这篇文章只是简单的做一个记录,仿制以后做网站的时候需要了,还要四处找教程,Nginx是非常优秀的网站环境架构系统,和Apache、IIS一样,非常受网站爱好者或者一些大型网站管理员的青睐,下面先来说一下我们先要实现的目的

起源与一个美好的构想

我们先来看一下遇到的困境和想法

1
http://example.com --------------> https://www.example.com
1
https://example.com -------------> https://www.example.com
1
http://www.example.com ----------> https://www.example.com

也就是说,无论是客户端输入什么样子的域名,都需要最终转跳到

1
https://www.example.com

当然了, 前提是需要添加ssl证书,和网站支持代码设置。

实际操作起来的代码

1.我们需要再nginx的环境目录之中,也就是

1
/etc/nginx/conf.d

里面,新建一个配置文件,命名为example.com.conf

2.然后将下面的配置代码复制粘贴进去

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name example.com www.example.com;

return 301 https://www.example.com$request_uri;
}

server {
listen *:443 ssl;
listen [::]:443 ssl;
server_name example.com;

return 301 https://www.example.com$request_uri;
}

server {
listen *:443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com;

add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
add_header X-Frame-Options "DENY";

charset utf8;

access_log /var/log/nginx/*.example.com/access.log main;
error_log /var/log/nginx/*.example.com/error.log warn;

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

# ssl on;
ssl_certificate /etc/nginx/ssl/*.example.com.crt;
ssl_certificate_key /etc/nginx/ssl/*.example.com.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:!DH:!DHE;
ssl_prefer_server_ciphers on;

error_page 404 /404.html;
# location = /404.html {
# root /usr/share/nginx/html;
# }

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

其中需要注意的是,代码之中我们以

1
example.com

为例子,大家提前替换一下

3.然后将代码保存,并运行下面的命令,检测配置文件是否合规:

1
nginx -t

如果配置文件没有语法错误,一般会提示如下:

1
2
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重新运行下面的命令,重新加载 Nginx 配置文件,使修改生效

1
nginx -s reload

或者

1
systemctl reload nginx

经过上面的代码运行,我们的想法已经实现,希望能够帮助到大家!