前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Nginx配置自签证书强制跳转Https

Nginx配置自签证书强制跳转Https

原创
作者头像
冬夜读书示子聿
修改2022-01-09 21:15:34
7750
修改2022-01-09 21:15:34
举报
文章被收录于专栏:读书写字读书写字

Nginx 是世界上最受欢迎的 Web 服务器之一,负责托管互联网上一些最大和流量最高的站点。 这是一个轻量级的选择,可以用作 Web 服务器或反向代理。在公司内部,像Zabbix、ELK都可以通过Nginx实现Web端的管理。接下来,我将在 Ubuntu 20.04 服务器上安装 Nginx,创建自签名证书,设定访问https跳转,保障内网客户端浏览器与Web服务器之间的通讯安全。

  • VM环境:
代码语言:txt
复制
    ┌──────────────────────────────────────────────────────────────────────┐
    │                 • MobaXterm Personal Edition v21.2 •                 │
    │               (SSH client, X server and network tools)               │
    │                                                                      │
    │ ➤ SSH session to testuser@192.168.226.131                         │
    │   • Direct SSH      :  ✔                                             │
    │   • SSH compression :  ✔                                             │
    │   • SSH-browser     :  ✔                                             │
    │   • X11-forwarding  :  ✔  (remote display is forwarded through SSH)  │
    │                                                                      │
    │ ➤ For more info, ctrl+click on help or visit our website.            │
    └──────────────────────────────────────────────────────────────────────┘

Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.4.0-91-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat 04 Dec 2021 02:32:23 PM UTC

  System load:  0.06               Processes:               161
  Usage of /:   25.3% of 23.74GB   Users logged in:         1
  Memory usage: 6%                 IPv4 address for ens192: 192.168.226.131
  Swap usage:   0%
  • 所有源码安装包存放目录
代码语言:txt
复制
/home/testuser/source
  • 安装方式: 从源代码编译和安装 从源代码编译 NGINX 比预构建的包提供更多的灵活性:可以添加特定模块(来自 NGINX 或第三方),并应用最新的安全补丁。
  • 安装编译工具
代码语言:txt
复制
sudo apt-get update
sudo apt-get install build-essential
  • 安装 NGINX 依赖包 在从源代码编译 NGINX Open Source 之前,需要为其依赖项安装库:
    • PCRE——支持正则表达式,NGINX Core和Rewrite模块需要。
代码语言:txt
复制
$ wget https://sourceforge.net/projects/pcre/files/pcre/8.45/pcre-8.45.tar.gz
$ tar -zxf pcre-8.45.tar.gz
$ cd pcre-8.45
$ ./configure
$ make
$ sudo make install
代码语言:txt
复制
$ wget http://zlib.net/zlib-1.2.11.tar.gz
$ tar -zxf zlib-1.2.11.tar.gz
$ cd zlib-1.2.11
$ ./configure
$ make
$ sudo make install
代码语言:txt
复制
$ apt show openssl
Package: openssl
Version: 1.1.1f-1ubuntu2.9
Priority: important
Section: utils
Origin: Ubuntu
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Debian OpenSSL Team <pkg-openssl-devel@lists.alioth.debian.org>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 1,287 kB
Depends: libc6 (>= 2.15), libssl1.1 (>= 1.1.1)
Suggests: ca-certificates
Homepage: https://www.openssl.org/
Task: minimal
Download-Size: 622 kB
APT-Sources: http://cn.archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages
Description: Secure Sockets Layer toolkit - cryptographic utility

$ wget https://www.openssl.org/source/old/1.1.1/openssl-1.1.1f.tar.gz
$ tar -zxvf openssl-1.1.1f.tar.gz

如果你的系统没有安装过openssl,且想通过源码安装,可以执行以下命令:

代码语言:javascript
复制
$ wget https://www.openssl.org/source/openssl-1.1.1l.tar.gz
$ tar -zxf openssl-1.1.1l.tar.gz
$ cd openssl-1.1.1l
$ ./Configure darwin64-x86_64-cc --prefix=/us
$ make
$ sudo make install
  • 安装Nginx

从nginx.org下载稳定版的源码压缩包进行解压,创建自己想要的安装路径。

代码语言:javascript
复制
$ wget https://nginx.org/download/nginx-1.20.2.tar.gz
$ tar zxf nginx-1.20.2.tar.gz
$ cd nginx-1.20.2.0
$ sudo mkdir -p /usr/local/nginx/

编译参数解释

Parameter

Description

--prefix=<PATH>

Directory for NGINX files, and the base location for all relative paths set by the other configure script options (excluding paths to libraries) and for the path to the nginx.conf configuration file. Default: /usr/local/nginx.

--sbin-path=<PATH>

Name of the NGINX executable file, which is used only during installation. Default: **/sbin/nginx

--conf-path=<PATH>

Name of the NGINX configuration file. You can, however, always override this value at startup by specifying a different file with the -c <FILENAME> option on the nginx command line. Default: **conf/nginx.conf

--pid-path=<PATH>

Name of the nginx.pid file, which stores the process ID of the nginx master process. After installation, the path to the filename can be changed with the pid directive in the NGINX configuration file. Default: **/logs/nginx.pid

--error-log-path=<PATH>

Name of the primary log file for errors, warnings, and diagnostic data. After installation, the filename can be changed with the error_log directive in the NGINX configuration file. Default: **/logs/error.log

--http-log-path=<PATH>

Name of the primary log file for requests to the HTTP server. After installation, the filename can always be changed with the access_log directive in the NGINX configuration file. Default: **/logs/access.log

--user=<NAME>

Name of the unprivileged user whose credentials are used by the NGINX worker processes. After installation, the name can be changed with the user directive in the NGINX configuration file. Default: nobody

--group=<NAME>

Name of the group whose credentials are used by the NGINX worker processes. After installation, the name can be changed with the user directive in the NGINX configuration file. Default: the value set by the --user option.

--with-pcre=<PATH>

Path to the source for the PCRE library, which is required for regular expressions support in the location directive and the Rewrite module.

--with-pcre-jit

Builds the PCRE library with “just-in-time compilation” support (the pcre_jit directive).

--with-zlib=<PATH>

Path to the source for the zlib library, which is required by the Gzip module.

编译安装完成后,由于nginx的安装路径不在系统变量中,所以需要在用户家目录的.bashrc中设定$PATH变量,才能方便NGINX的启动、停止,重启:

代码语言:javascript
复制
sudo vim /home/testuser/.bashrc

#添加NGINX可执行文件的安装路径
export PATH="/usr/local/nginx/bin:$PATH"
#使其生效
source .bashrc

#启动NGINX
sudo /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
#设定NGINX开机自启动
cd lib/systemd/system
#在该目录下创建nginx.service
vim nginx.service

#添加以下脚本内容
[Unit]
Description=nginx - high performance web serve
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
[Install]
WantedBy=multi-user.target

#设置开机自动启动
systemctl enable nginx.service
#重启nginx服务
systemctl restart nginx.service

[Unit]服务说明 After:依赖,当依赖的服务启动之后再启动自定义的服务 Type=forking是后台运行的形式

  • 确认安装结果
    • 检查NGINX开放端口:
代码语言:javascript
复制
sudo netstat -antup | grep 80
[sudo] password for test01:
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      161759/nginx: maste
  • 创建自签名证书

证书是由证书颁发机构或 CA进行数字签名。CA 是已确认证书中包含的信息准确无误的受信任第三方。对于拥有域名和公网IP的正常服务器来说,使用受信机构签名的证书是最好的选择。 但对于用于内网环境,或者是没有域名的测试服务器而言,自签名证书是折中的选择。接下来我将通过CA根证书签名服务器证书的方式创建SSL证书,一般来讲创建自签名证书有以下几个步骤:

  • 在/usr/local/nginx/中创建certs目录,并在该目录创建私有和公共加密密钥对

代码语言:javascript
复制
openssl genrsa -des3 -out server.key 2048

输入要求有复杂性的密码,且至少包含八个字符。创建好的服务器密钥会生成并存储在server.key文件中。

  • 创建没有加密的密钥对

代码语言:javascript
复制
openssl rsa -in server.key -out server.key.insecure
mv server.key server.key.secure
mv server.key.insecure server.key

不安全的密钥现在被命名为server.key

  • 创建证书签名请求

代码语言:javascript
复制
openssl req -new -key server.key -out server.cs
代码语言:javascript
复制
    server {
        listen       80;
        listen 443   ssl;
        server_name  192.168.226.131;
        ssl_certificate      /usr/local/nginx/certs/server.crt;
        ssl_certificate_key  /usr/local/nginx/certs/server.key;
代码语言:javascript
复制
if ($scheme = 'http') {
        return 301 https://$host$request_uri;
        }

Nginx配置文件概览:

代码语言:javascript
复制
cat nginx.conf|grep -Ev '^$|#'
worker_processes  1;
pid        logs/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        listen 443   ssl;
        server_name  192.168.226.131;
        ssl_certificate      /usr/local/nginx/certs/zabbix.test.com.crt;
        ssl_certificate_key  /usr/local/nginx/certs/server.key;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        if ($scheme = 'http') {
        return 301 https://$host$request_uri;
        }
        location = /50x.html {
            root   html;
        }
    }
}
  • 重启NGINX服务,并在Web页面访问验证结果,输入http://192.168.226.131/,自动跳转https://192.168.226.131/:
代码语言:javascript
复制
systemctl restart nginx

进阶:如果想创建自己的内部CA,签发自签名证书,可以按以下步骤:

  • 创建目录以保存 CA 证书和相关文件
代码语言:javascript
复制
sudo mkdir /etc/ssl/CA
sudo mkdir /etc/ssl/newcerts
  • CA 需要一些额外的文件来操作,一个用于跟踪 CA 使用的最后一个序列号,每个证书必须有一个唯一的序列号,另一个文件用于记录哪些证书已颁发:
代码语言:javascript
复制
sudo sh -c "echo '01' > /etc/ssl/CA/serial"
sudo touch /etc/ssl/CA/index.txt
  • 第三个文件是 CA 配置文件。虽然不是绝对必要,但在签发多个证书时非常方便。编辑/etc/ssl/openssl.cnf,并在[ CA_default ]更改:
代码语言:javascript
复制
dir             = /etc/ssl              # Where everything is kept
database        = $dir/CA/index.txt     # database index file.
certificate     = $dir/certs/cacert.pem # The CA certificate
serial          = $dir/CA/serial        # The current serial numbe
private_key     = $dir/private/cakey.pem# The private key
  • 创建自签名根证书
代码语言:javascript
复制
openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650
  • 安装根证书和密钥:
代码语言:javascript
复制
sudo mv cakey.pem /etc/ssl/private/
sudo mv cacert.pem /etc/ssl/certs/
  • 为服务端应用签署、颁发证书
代码语言:javascript
复制
sudo openssl ca -in server.csr -config /etc/ssl/openssl.cnf

输入 CA 密钥的密码后,系统将会提示签署证书,并再次提交新证书。然后,我们应该会看到与证书创建相关的大量输出。随后就会有一个/etc/ssl/newcerts/01.pem包含相同输出的新文件。创建新的证书文件,如zabbix.test.com.cert,复制并粘贴01.pem中以—BEGIN CERTIFICATE—开头,—END CERTIFICATE-----结结尾的所有内容。以后为其他服务器域名申请的证书将被命名为02.pem,03.pem等。

  • 将新证书复制到特定目录,如/usr/local/nginx/certs,并配置相应的应用程序使其生效。
  • 在浏览器中验证自签名证书与内部CA证书颁发的证书.

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
SSL 证书
腾讯云 SSL 证书(SSL Certificates)为您提供 SSL 证书的申请、管理、部署等服务,为您提供一站式 HTTPS 解决方案。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档