Linux Nginx安装部署说明_Linux搭建Nginx服务器步骤

3次阅读

linux安装 nginx 推荐用包管理器:centos/RHEL 执行 yum 或 dnf install nginx,ubuntu/debian 执行 apt install nginx;安装后需 systemctl start 并 enable 服务,配置 防火墙 ,验证 80 端口 监听及首页访问,修改配置须 nginx - t 测试后 reload。

Linux Nginx 安装部署说明_Linux 搭建 Nginx 服务器步骤

Linux 上安装部署 Nginx 并不复杂,关键是选对方式、配好基础配置、确保服务能正常启停和响应请求。下面按实际操作逻辑分步说明,覆盖主流发行版(CentOS/RHEL 7+、Ubuntu/Debian)。

一、选择安装方式:包管理器 vs 源码编译

推荐优先使用系统包管理器安装,省心、安全、易更新;仅当需要特定模块(如 ngx_brotli)、最新版或深度定制时才考虑源码编译。

  • CentOS/RHEL:执行 sudo yum install nginx(8+ 系统用 dnf install nginx
  • Ubuntu/Debian:执行 sudo apt update && sudo apt install nginx
  • 安装后验证:nginx -v 查版本,systemctl status nginx 看是否已安装但未启动

二、启动并设为开机自启

Nginx 安装后默认不自动运行,需手动启用。

  • 启动服务:sudo systemctl start nginx
  • 设为开机自启:sudo systemctl enable nginx
  • 检查监听状态:sudo ss -tlnp | grep :80(应看到 nginx 占用 80 端口
  • 打开 防火墙(如启用):sudo firewall-cmd –permanent –add-service=http(CentOS)或 sudo ufw allow ‘Nginx Full’(Ubuntu)

三、确认首页访问 & 基础配置路径

安装成功后,默认网页根目录是 /usr/share/nginx/html,主配置文件在 /etc/nginx/nginx.conf

  • 浏览器 访问服务器 IP 或域名,应看到“Welcome to nginx!”页面
  • 常用子配置目录:/etc/nginx/conf.d/(放 site 配置,如 default.confmyapp.conf
  • 修改配置后务必测试:sudo nginx -t(语法检查),再重载:sudo systemctl reload nginx

四、简单反向代理示例(快速上手)

比如把 http://your-domain.com/api 转发到本地 3000 端口的服务:

  • /etc/nginx/conf.d/myapp.conf 中写入:

server {
  listen 80;
  server_name your-domain.com;

  location /api/ {
    proxy_pass http://127.0.0.1:3000/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}

  • 保存后运行 sudo nginx -t && sudo systemctl reload nginx
  • 注意:proxy_pass 末尾斜杠影响路径重写,要保持一致

基本上就这些。后续可按需配置 https(用 Certbot)、负载均衡、静态资源缓存等。不复杂但容易忽略 reload 和防火墙,动手前多 check 两遍。

站长
版权声明:本站原创文章,由 站长 2025-12-22发表,共计1365字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
1a44ec70fbfb7ca70432d56d3e5ef742
text=ZqhQzanResources