简述部署 Nginx步骤

2024-03-25  本文已影响0人  Reone_JS

查看安装路径 whereis nginx
查看进程 ps aux | grep nginx
检查端口:netstat -tuln

1. 安装依赖插件

yum -y install gcc pcre pcre-devel zlib zlib-devel 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 协议。Nginx 不仅支持 HTTP 协议,还支持 HTTPS,因此需要在 CentOS 安装 OpenSSL 库。

2. 安装 wget

yum install wget

3. 安装 Nginx

下载 Nginx

wget https://nginx.org/download/nginx-1.25.4.tar.gz

解压 Nginx

tar xvf nginx-1.25.4.tar.gz
cd nginx-1.25.4

配置 Nginx(包含 HTTPS 模块)

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

编译和安装 Nginx

make
make install

查看安装路径

whereis nginx 
# 结果:(路径:nginx: /usr/local/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

说明:

注意:[Service] 下的启动、重启、停止命令全部要求使用绝对路径。

加入开机自启动

systemctl enable nginx.service

4. 服务的管理

# 启动 Nginx 服务
systemctl start nginx.service

# 停止 Nginx 服务
systemctl stop nginx.service

# 重新启动 Nginx 服务
systemctl restart nginx.service

# 查看所有已启动的服务
systemctl list-units --type=service

# 查看 Nginx 服务当前状态
systemctl status nginx.service

# 设置 Nginx 开机自启动
systemctl enable nginx.service

# 停止 Nginx 开机自启动
systemctl disable nginx.service

5. Nginx 配置

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

6. 开放端口

防火墙配置

firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --zone=public --add-port=443/tcp --permanent

重启防火墙和 Nginx

systemctl restart firewalld.service
systemctl restart nginx.service

7. 修改安全组

在云服务器配置页开放端口。

上一篇 下一篇

猜你喜欢

热点阅读