插件窝 干货文章 Centos7下nginx怎么安装与配置

Centos7下nginx怎么安装与配置

Nginx sudo 配置 systemctl 322    来源:    2025-04-21

CentOS 7 下 Nginx 的安装与配置指南

一、安装 Nginx

方法1:使用 EPEL 仓库安装(推荐)

  1. 添加 EPEL 仓库:

    sudo yum install epel-release
    
  2. 安装 Nginx:

    sudo yum install nginx
    
  3. 启动 Nginx 服务:

    sudo systemctl start nginx
    
  4. 设置开机启动:

    sudo systemctl enable nginx
    

方法2:从官方仓库安装(获取最新版本)

  1. 创建 Nginx 官方仓库文件:

    sudo vi /etc/yum.repos.d/nginx.repo
    
  2. 添加以下内容:

    [nginx]
    name=nginx repo
    baseurl=http://nginx.org/packages/centos/7/$basearch/
    gpgcheck=0
    enabled=1
    
  3. 安装 Nginx:

    sudo yum install nginx
    
  4. 启动并设置开机启动:

    sudo systemctl start nginx
    sudo systemctl enable nginx
    

二、基本配置

1. 防火墙配置

允许 HTTP(80) 和 HTTPS(443) 端口:

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

2. 测试安装

在浏览器访问服务器 IP 地址,应看到 Nginx 欢迎页面。

3. 主要配置文件

  • 主配置文件:/etc/nginx/nginx.conf
  • 默认服务器配置:/etc/nginx/conf.d/default.conf
  • 自定义站点配置:建议在 /etc/nginx/conf.d/ 目录下创建单独的 .conf 文件

三、配置虚拟主机(多站点)

  1. 创建站点配置文件:

    sudo vi /etc/nginx/conf.d/example.com.conf
    
  2. 添加基本配置示例:

    server {
       listen 80;
       server_name example.com www.example.com;
    
       root /var/www/example.com/html;
       index index.html index.htm;
    
       location / {
           try_files $uri $uri/ =404;
       }
    
       error_page 500 502 503 504 /50x.html;
       location = /50x.html {
           root /usr/share/nginx/html;
       }
    }
    
  3. 创建网站目录并设置权限:

    sudo mkdir -p /var/www/example.com/html
    sudo chown -R $USER:$USER /var/www/example.com/html
    sudo chmod -R 755 /var/www
    
  4. 创建测试页面:

    echo "<h1>Welcome to Example.com</h1>" > /var/www/example.com/html/index.html
    
  5. 测试配置并重启 Nginx:

    sudo nginx -t  # 测试配置语法
    sudo systemctl restart nginx
    

四、常用命令

  • 启动 Nginx:sudo systemctl start nginx
  • 停止 Nginx:sudo systemctl stop nginx
  • 重启 Nginx:sudo systemctl restart nginx
  • 重新加载配置(不中断服务):sudo systemctl reload nginx
  • 检查配置语法:sudo nginx -t
  • 查看状态:sudo systemctl status nginx

五、日志文件位置

  • 访问日志:/var/log/nginx/access.log
  • 错误日志:/var/log/nginx/error.log

六、SSL 配置(HTTPS)

  1. 安装 certbot(Let's Encrypt 客户端):

    sudo yum install certbot python2-certbot-nginx
    
  2. 获取并安装证书:

    sudo certbot --nginx -d example.com -d www.example.com
    
  3. 设置自动续期:

    sudo certbot renew --dry-run
    

七、性能优化(可选)

/etc/nginx/nginx.confhttp 块中添加以下配置:

# 调整工作进程数(通常等于CPU核心数)
worker_processes auto;

# 每个工作进程的最大连接数
events {
    worker_connections 1024;
}

# 启用Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

希望这个指南能帮助您在 CentOS 7 上成功安装和配置 Nginx!如有任何问题,可以查看 Nginx 日志文件获取更多调试信息。