CentOS系统安装配置Nginx Web服务器教程
常见问题 · 服务器问题
Nginx是目前最流行的Web服务器之一,以其高性能、低内存占用和优秀的并发处理能力著称。本文将介绍在CentOS系统上从零开始安装并配置Nginx的完整流程。
一、安装Nginx
推荐从官方源安装以获得最新稳定版本:
# CentOS/RHEL 系列
yum install -y epel-release
yum install -y nginx
# Ubuntu/Debian 系列
apt update
apt install -y nginx
安装完成后启动Nginx并设置开机自启:
systemctl start nginx
systemctl enable nginx
systemctl status nginx
此时访问 http://服务器IP,应该能看到Nginx的默认欢迎页面。
二、防火墙放行Web端口
# CentOS 使用 firewalld
firewall-cmd --add-service=http --permanent
firewall-cmd --add-service=https --permanent
firewall-cmd --reload
# Ubuntu 使用 ufw
ufw allow 80/tcp
ufw allow 443/tcp
三、配置虚拟主机
cat > /etc/nginx/conf.d/example.com.conf << 'EOF'
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm index.php;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri $uri/ /index.html;
}
}
EOF
测试配置并重载:
nginx -t # 测试配置文件
systemctl reload nginx # 平滑重载
四、配置HTTPS(SSL证书)
推荐使用免费的Let's Encrypt证书:
# 安装Certbot
yum install -y certbot python3-certbot-nginx # CentOS
apt install -y certbot python3-certbot-nginx # Ubuntu
# 自动申请并配置SSL
certbot --nginx -d example.com -d www.example.com
五、性能优化建议
- 调整worker进程数:worker_processes auto;(自动匹配CPU核心数)
- 开启gzip压缩:gzip on; gzip_types text/plain text/css application/json;
- 配置静态文件缓存:location ~* \.(jpg|png|css|js)$ { expires 30d; }
- 限制连接数防止资源耗尽
关键词:Nginx、Web服务器、HTTPS、反向代理 | 八彩云技术分享 · 仅供学习参考
注册
登录控制台
