Nginx 从软件源安装与配置
slug
nginx-setup-from-repo
tags
nginx
apt
yum
date
Aug 3, 2024
summary
使用 apt 或者 yum 包管理器安装与配置 Nginx。
status
Published
type
Post
一、安装
1.1. 安装依赖
# ubuntu sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring # debian sudo apt install curl gnupg2 ca-certificates lsb-release debian-archive-keyring # Fedora/RHEL/CentOS sudo yum install yum-utils
1.2. 添加软件源
# On Fedora/RHEL/CentOS: sudo sh -c "cat > /etc/yum.repos.d/nginx.repo" <<EOF [nginx-stable] name=nginx stable repo baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true [nginx-mainline] name=nginx mainline repo baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/ gpgcheck=1 enabled=0 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true EOF
# Ubuntu/Debian: curl <https://nginx.org/keys/nginx_signing.key> | gpg --dearmor \ | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null # Debian echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \ <http://nginx.org/packages/debian> `lsb_release -cs` nginx" \ | sudo tee /etc/apt/sources.list.d/nginx.list # Ubuntu echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \ <http://nginx.org/packages/ubuntu> `lsb_release -cs` nginx" \ | sudo tee /etc/apt/sources.list.d/nginx.list
1.3. 安装运行
# On Fedora/RHEL/CentOS: sudo yum-config-manager --enable nginx-mainline sudo yum install nginx # On Ubuntu/Debian: sudo apt update sudo apt install nginx
1.4. 防火墙设置
sudo firewall-cmd --permanent --zone=public --add-service=http sudo firewall-cmd --permanent --zone=public --add-service=https sudo firewall-cmd --reload
二、配置
默认配置文件路径
- 默认网站根目录
/usr/share/nginx/html
- 默认网站根配置文件
/etc/nginx/conf.d/default.conf
- 其他网站配置文件
/etc/nginx/conf.d/
- 全局配置文件
/etc/nginx/nginx.conf
新建额外配置目录
mkdir -p /etc/nginx/{sites-available,sites-enabled,conf.d,rewrite-rules,ssl-certs} && \ chmod 755 /etc/nginx/{sites-available,sites-enabled,conf.d,rewrite-rules,ssl-certs}
# vim /etc/nginx/nginc.conf nclude /etc/nginx/sites-enabled/*.conf;
SSL 证书目录
chmod 777 /etc/nginx/ssl-certs && \ chmod o+t /etc/nginx/ssl-certs openssl dhparam -out /etc/nginx/ssl-certs/dhparam.pem 2048 curl <https://ssl-config.mozilla.org/ffdhe2048.txt> > /etc/nginx/ssl-certs/dhparam.pem
运行 Nginx
查看主机IP地址
ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\\/.*$//'
运行
sudo systemctl enable --now nginx