系统更新:
sudo dnf update -y
安装EPEL仓库(如果需要安装最新版本的Nginx):
sudo dnf install epel-release -y
安装Nginx:
sudo dnf install nginx -y
启动并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
创建Nginx仓库文件:
sudo vi /etc/yum.repos.d/nginx.repo
添加以下内容:
[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:
sudo dnf install nginx -y
bash
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
检查Nginx状态:
sudo systemctl status nginx
访问测试页面: 在浏览器中输入服务器IP地址,应该能看到Nginx欢迎页面。
如果遇到端口80被占用:
sudo netstat -tulnp | grep :80
然后终止占用端口的进程或修改Nginx监听端口。
如果SELinux阻止Nginx运行:
sudo setsebool -P httpd_can_network_connect 1
检查错误日志:
sudo journalctl -xe
sudo tail -f /var/log/nginx/error.log
创建服务器块(类似Apache的虚拟主机):
sudo vi /etc/nginx/conf.d/example.com.conf
添加以下内容:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
创建网站目录:
sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/example.com/html
测试配置并重启Nginx:
sudo nginx -t
sudo systemctl restart nginx
调整worker进程数(在/etc/nginx/nginx.conf中):
worker_processes auto;
启用Gzip压缩:
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
设置缓存头:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
}
以上是在CentOS 8上安装和配置Nginx的完整流程。根据您的具体需求,可能还需要进行其他配置调整。