环境准备
虚拟机一台:
centos8
IP:172.16.183.18
关闭防火墙(为了测试)
systemctl status firewalld.service(查看防火墙状态)
systemctl stop firewalld.service (关闭防火墙)
systemctl start firewalld.service (开启防火墙)
systemctl disable firewalld.service (禁止防火墙自启动)
systemctl enable firewalld.service (防火墙随系统开启启动)
#一次安装4个插件
yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
#一次安装如果有问题,可以试一下分开安装(上面命令执行成功了就就无需执行以下命令了)
yum install gcc-c++
yum install -y pcre pcre-devel
yum install -y zlib zlib-devel
yum install -y openssl openssl-devel
安装的插件的作用
1.gcc 可以编译 C,C++,Ada,Object C和Java等语言(安装 nginx 需要先将官网下载的源码进行编译,编译依赖 gcc 环境)
2.pcre pcre-devel pcre是一个perl库,包括perl兼容的正则表达式库,nginx的http模块使用pcre来解析正则表达式,所以需要安装pcre库
3.zlib zlib-devel zlib库提供了很多种压缩和解压缩方式nginx使用zlib对http包的内容进行gzip,所以需要安装
4.openssl openssl-devel OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及 SSL 协议,并提供丰富的应用程序供测试或其它目的使用。
5.nginx 不仅支持 http 协议,还支持 https(即在ssl协议上传输http),所以需要在 Centos 安装 OpenSSL 库
安装步骤
安装nginx
方法一、 直接下载.tar.gz安装包 https://nginx.org/en/download.html
方法二、使用wget命令下载(推荐)。确保系统已经安装了wget,如果没有安装,执行 yum install wget 安装。
(注意:本示例使用方法一)
- 下载包
wgte https://nginx.org/download/nginx-1.21.6.tar.gz
- 解压
tar xvf nginx-1.21.6.tar.gz
cd nginx-1.21.6
- 配置(带有https模块)
./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
- 编译和安装
编译:make
安装:make install
- 查看安装路径
whereis nginx
- 设置开机启动
编辑服务文件
vim /lib/systemd/system/nginx.service
[Unit]
Description=nginx service
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
说明:
Description:描述服务
After:描述服务类别
[Service]服务运行参数的设置
Type=forking是后台运行的形式
ExecStart为服务的具体运行命令
ExecReload为重启命令
ExecStop为停止命令
PrivateTmp=True表示给服务分配独立的临时空间
注意:[Service]的启动、重启、停止命令全部要求使用绝对路径
[Install]运行级别下服务安装的相关设置,可设置为多用户,即系统运行级别为3
保存退出
加入开机自启动
systemctl enable nginx.service
取消开机自启动
systemctl disable nginx.service
服务的启动/停止/刷新配置文件/查看状态
#启动nginx服务
systemctl start nginx.service
#停止服务
systemctl stop nginx.service
#重新启动服务
systemctl restart nginx.service
#查看所有已启动的服务
systemctl list-units --type=service
#查看服务当前状态
systemctl status nginx.service
#设置开机自启动
systemctl enable nginx.service
# 停止开机自启动
systemctl disable nginx.service
nginx.conf https 配置
server {
listen 443 ssl;
server_name localhost;
ssl_certificate cert.pem;#根证书地址(默认把证书放在conf目录)
ssl_certificate_key cert.key;#证书秘钥(默认把证书放在conf目录)
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
将 http 重定向 https
server {
listen 80;
server_name localhost;
#将请求转成https
rewrite ^(.*) https://$server_name$1 permanent;
}
查看nginx 进程命令
ps aux | grep nginx
html设置编码
html文件显示出来乱码,一般在文件头中设置网页编码即可,加入<meta charset="utf-8">