CentOS7 安装配置 nginx

安装 nginx

检查是否已安装:

rpm -qa | grep nginx

如果没有,先添加软件源(CentOS 7 默认没有 nginx 软件源)再安装:

# 添加 nginx 软件源
sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

# 安装 nginx
sudo yum -y install nginx

如果有,则更新 nginx:

sudo yum -y upgrade nginx

查看安装的 nginx 版本:

nginx -v

nginx version: nginx/1.16.1

启动 nginx

启动 nginx 服务:

sudo systemctl start nginx

设置 nginx 服务开机启动:

查看 nginx 守护进程状态:

● nginx.service - nginx - high performance web server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since 四 2019-08-15 17:04:20 UTC; 18s ago Docs: http://nginx.org/en/docs/ Main PID: 1540 (nginx) CGroup: /system.slice/nginx.service ├─1540 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf └─1541 nginx: worker process

FirewallD 配置

查看默认区域永久配置:

public target: default icmp-block-inversion: no interfaces: sources: services: ssh ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:

可见 services: ssh 表示只添加了 ssh 服务,ports: 中也没有添加 80/tcp 端口。

如果 ports 中永久添加了 80/tcp ,则永久删除:

永久添加 http 服务到当前默认区域:

重载防火墙规则:

Tips:

  • 阿里云 ECS 需要在控制台的安全组策略中添加入方向的 80/tcp 端口。

  • 阿里云轻量应用主机需要在控制台的防火墙中添加 80/tcp 端口。

访问测试

在浏览器中使用服务器 IP 地址访问,看到 nginx 的欢迎页面即说明设置成功。

可以自行修改该欢迎页面:

安全设置

隐藏 nginx 版本号

修改 nginx 主配置文件:

找到:

server 域里面插入配置:

保存退出,重启 nginx 服务:

此时 nginx 返回信息不会再显示具体版本号。

禁止使用 IP 访问

修改 nginx 默认配置文件 :

找到:

改成:

保存退出,重启 nginx 服务:

此时使用 IP 访问会显示 400 Bad Request

Tips:/etc/nginx/conf.d 目录中创建的 .conf 配置文件会自动被 nginx 加载。

参考文献

Last updated

Was this helpful?