Linux(CentOS7举例) 安装Nginx教程

在 CentOS 系统上安装 Nginx 可以通过以下步骤进行:

安装 Nginx

  1. 更新系统包
    首先,你可以通过运行以下命令来确保你的系统包是最新的:

    sudo yum update
    

    • 1
  2. 安装 EPEL 仓库
    Nginx 通常位于 EPEL (Extra Packages for Enterprise Linux) 仓库中。你可以用以下命令安装 EPEL 仓库:

    sudo yum install epel-release
    

    • 1
  3. 安装 Nginx
    接下来,安装 Nginx:

    sudo yum install nginx
    

    • 1
  4. 启动 Nginx
    安装完成后,可以启动 Nginx 服务:

    sudo systemctl start nginx
    

    • 1
  5. 设置 Nginx 开机自启动
    为了确保 Nginx 在系统重启后自动启动,你可以使用以下命令:

    sudo systemctl enable nginx
    

    • 1
  6. 允许 HTTP 和 HTTPS 流量
    如果你的防火墙正在运行,你需要允许 HTTP 和 HTTPS 流量。可以使用以下命令:

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

    • 1
    • 2
    • 3
  7. 验证 Nginx 是否安装成功
    在浏览器中输入你的服务器 IP 地址(或 http://localhost),如果 Nginx 安装成功,你将看到默认的 Nginx 欢迎页面。

配置 Nginx

Nginx 的配置文件位于 /etc/nginx/nginx.conf,你可以根据需要修改它。相关的站点配置文件通常位于 /etc/nginx/conf.d/ 目录下, 如:

cd /etc/nginx/conf.d
touch default.conf

  • 1
  • 2

配置内容如下:

server {
    listen 8080;
    server_name 106.54.209.14;  # 内网服务器可以使用 localhost 或者服务器的内网IP

    location / {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
        add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,Content-Type';
        proxy_pass http://127.0.0.1:8081;  # 如果后端服务在同一台机器上
        # 或者使用实际的后端服务地址
        # proxy_pass http://后端服务IP:端口/api/test;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

常见命令

  • 重启 Nginx

    sudo systemctl restart nginx
    

    • 1
  • 停止 Nginx

    sudo systemctl stop nginx
    

    • 1
  • 查看 Nginx 状态

    sudo systemctl status nginx
    

    • 1

通过以上步骤,你就可以在 CentOS 上成功安装和运行 Nginx。这是一个基本的安装过程,可以根据你具体的需求进行进一步的配置。

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...