首页  /  Web 应用服务  /  正文

Nginx 安装与配置文件上手

Web 应用服务 2026-10-01📖 16 分钟👁 —
🌐 Web 应用服务 · Nginx第 1 / 8 页12345678📖 完整导航 →

一、安装

Nginx 主要分 Nginx(nginx.org) 开源版、Nginx plus(www.nginx.com) 商业版,和下面两个。

学习用 OpenResty 版本和开源版,官方站点是 openresty.org。

基础部分先用 Nginx,了解大概之后使用 OpenResty。

用途:反向代理、集群的负载均衡(这块更适合 Tengine 版本,tengine.taobao.org)。

操作前后可以备份(快照),如果 clone,连接克隆就可以。

安装注意 —— 在 ubuntu 云上安装,需要 root:

apt update ; apt -y install nginx
systemctl enable --now nginx

默认安装在 etc 下,配置文件是 /etc/nginx/nginx.conf。

nginx 默认使用 80 和 443 端口提供服务,上云要配置规则。

一种是直接调二进制(/usr/sbin/nginx -s reload),适合源码编译安装、排错;另一种是走 systemd 服务管理(systemctl restart nginx),是 apt/yum 安装的用法。按照习惯使用 systemd 服务管理即可。

# 启动
./nginx
# 优雅重载配置(不中断服务)
./nginx -s reload
# 停止
./nginx -s stop
# 测试配置文件语法
./nginx -t
# systemctl版
systemctl start/restart/reload/stop/status nginx

关闭防火墙 systemctl stop firewalld.service

禁止防火墙开机启动 systemctl disable firewalld.service

Ubuntu 的服务叫 ufw(Ubuntu Firewall),centos 才是 firewall.service。

中小公司一般不会开内网防火墙的,除非要防止内部人员搞事情。

# Centos的操作
firewall-cmd --zone=public --add-port=80/tcp --permanent
# 开放端口
firewall-cmd --reload

# Ubuntu的操作
ufw allow 80/tcp
# 常见命令
ufw status/enable/reload

下面示例:

# 1. 开放 80 端口(HTTP)
firewall-cmd --zone=public --add-port=80/tcp --permanent

# 2. 开放 443 端口(HTTPS,可选)
firewall-cmd --zone=public --add-port=443/tcp --permanent

# 3. 重新加载防火墙规则
firewall-cmd --reload

# 4. 验证是否生效
firewall-cmd --list-ports # 可以配合grep

浏览器直接访问服务器 IP 默认走 80 端口,此前是 jumpserver 接管,所以是堡垒机的页面。nginx 默认页面也是使用 80 端口的,如果不想冲突,可以修改端口,也可以暂时停止 jumpserver,或者修改 jumpserver 端口(不推荐)。

修改 nginx 为 8080 端口:

# 编辑配置文件
sudo vi /etc/nginx/sites-enabled/default

listen 80 default_server;
listen [::]:80 default_server;
# 上面的配置修改为下面的
listen 8080 default_server;
listen [::]:8080 default_server;
ss -tuln | grep 8080 # 确认nginx在监听8080端口
tcp   LISTEN 0      511                           0.0.0.0:8080      0.0.0.0:*          
tcp   LISTEN 0      511                              [::]:8080         [::]:* 

访问本地地址端口为 8080,如果返回了 nginx 默认的页面就是成功了:

改完端口后访问到 nginx 默认页面

服务器规则配置的 8080 是堡垒机的,为什么能访问成功呢? 因为安全组里 8080 标成 "jumpserver" 只是备注名,不代表只能给 JumpServer 用;nginx 监听 8080 就是 nginx 在提供服务,谁监听谁用。


二、目录结构

因为 Ubuntu apt 安装的 Nginx 默认网页目录不在 /etc/nginx/ 下,在 /var/www/html/。这里建议直接复制一个 ssh 标签页操作,这样分别在配置目录和网页目录操作会方便很多哦,不用切来切去的。

在 nginx 安装的目录下,其中 nginx.conf 是配置文件,nginx.conf 是主配置文件,里面可以引用 conf.d 目录下的配置。

html 是 nginx 的站点资源,其中 index.html 是默认配置,可以通过 IP 和端口访问,也可以通过 IP:port/index.html 访问(这个要看防火墙规则了),本目录只能放一个站点,所以后面肯定会修改。

log 会记录访问流量,文件较大(access.log 这个文件写满了就会无限制报错)、记录系统出错的流量(error.log)。

可以查看 ps -ef | grep nginx 查看进程。

由于 jumpserver 的 web 组件是 nginx,所以查看端口会看到两组 nginx,不需要单独关,怎么区分下板块会有。

某次查看端口的情况:

root        2231    2021  0 Mar27 ?        00:00:00 nginx: master process nginx -g daemon off;
# daemon off后台运行的这个是apt安装的nginx
systemd+    2867    2231  0 Mar27 ?        00:00:51 nginx: worker process
systemd+    2868    2231  0 Mar27 ?        00:00:50 nginx: worker process
systemd+    2869    2231  0 Mar27 ?        00:00:07 nginx: cache manager process
root     1183857       1  0 20:09 ?        00:00:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
# daemon on前台运行的这个是jumpservre
www-data 1183858 1183857  0 20:09 ?        00:00:00 nginx: worker process
www-data 1183859 1183857  0 20:09 ?        00:00:00 nginx: worker process
root     1238665 1114507  0 20:37 pts/0    00:00:00 grep --color=auto nginx

daemon = 守护进程 = 后台运行的程序。

linux 的 /usr/local 目录和 win 的 /Program Files 是类似的,所以有的软件/服务会安装在这里部分,看个人习惯哦。

主要目录就是这几个:/etc/nginx/ 是主配置目录,/etc/nginx/nginx.conf 是主配置文件,/etc/nginx/sites-available/ 放站点配置(可用),/etc/nginx/sites-enabled/ 放站点配置(启用),/var/www/html/ 是默认网站根目录,/var/log/nginx/ 是日志目录,/usr/sbin/nginx 是可执行文件。

使用默认的 apt 安装,目录结构符合 linux 的规范,指定在某个目录下,就都在一起,方便管理,但也会造成部分麻烦。

平时查的时候,配置目录用 sudo nginx -t,网页文件用 ls -la /var/www/html/,日志用 sudo tail -f /var/log/nginx/access.log,可执行文件用 nginx -v。

补充 /etc/nginx/sites-enabled/default 是之前修改 nginx 端口的目录,原本是 80,改为 8080。


三、流量介绍和 nginx.conf 配置

Nginx 的进程

在开启 nginx 服务后会启用 master 主进程,读取配置文件、校验。

然后开启 worker 子进程,ps -ef | grep nginx 可以看到:

root        2231    2021  0 Mar27 ?        00:00:00 nginx: master process nginx -g daemon off;
systemd+    2867    2231  0 Mar27 ?        00:00:54 nginx: worker process
systemd+    2868    2231  0 Mar27 ?        00:00:53 nginx: worker process
systemd+    2869    2231  0 Mar27 ?        00:00:07 nginx: cache manager process

root     1183857       1  0 Apr16 ?        00:00:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data 1183858 1183857  0 Apr16 ?        00:00:00 nginx: worker process
www-data 1183859 1183857  0 Apr16 ?        00:00:00 nginx: worker process
root     2834977 2717696  0 15:42 pts/0    00:00:00 grep --color=auto nginx

两组的区别:JumpServer 的 nginx 父进程不是 1(是容器进程),启动参数是 daemon off(容器必须前台),master 是 root、worker 是 systemd+,PID 小(2231,启动早);系统 nginx 父进程是 1,启动参数是 daemon on(守护进程),master 是 root、worker 是 www-data,PID 大(1183857,启动晚)。

下面是请求解析的进程流程图,其中目录根据具体情况会有不同:

master 读配置、worker 接请求的流程图

多进程同时完成用户请求,主进程负责协调子进程。

Nginx 配置文件(重要)

/etc/nginx/nginx.conf 里是 http 块(全局配置);/etc/nginx/sites-enabled/default 里是 server 块 + location 块。

默认配置文件 /etc/nginx/nginx.conf

其中分为两部分来看,带 #(未生效)和生效的。

先简单了解一些核心配置,后面再深入,其中中文注释是笔记,其余为默认自带:

user www-data;
# nginx的启动用户
worker_processes auto;
# 默认自动开启进程(worker是子进程),可以改为数字
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # 每一个worker进程可以创建多少连接

        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        # 数据零拷贝,免除了像U盘一样的拷贝过程,直接传输到客户端(进阶调优部分会提到)
        keepalive_timeout 65s;
        # 请求超时时间,是我手动写入的,原本是默认开启的
        tcp_nopush on;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        # 可以把另外的配置文件引入到当前文件中
        # 比如不希望在一个配置文件写很多行就可以这样干,便于维护
        # mime.type写了HTTP响应类型(服务器-->浏览器)
        # 具体响应格式在mime.types中
        # 如果自定义了后缀比如mp5,也可以写入mime.types文件,以指定方式展示
        
        default_type application/octet-stream;
        # 默认类型,如果在mime.types之外的格式,就按照指定格式流的方式传输给客户端
        
        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#

# 主机
# 一个主机和多个主机都可以交给nginx管理,一个server就是一个主机,可以通过端口号区分主机
# 称为虚拟主机,virtual host,简称vhost
#       server {
#               listen     localhost:110;
                # 监听的当前一个主机的端口号和主机名,主机名写域名也可,必须要能够解析
                # 如:在主机映射文件记录了localhost为127...
#               protocol   pop3;
#               proxy      on;
#       }
# server的站点配置文件在下个代码块中
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

sites-available 存放所有站点配置文件,sites-enabled 存放激活的站点配置,一个像仓库一个像货架。

sites-enabled 里的文件是 sites-available 的软链接(快捷方式):

sudo ln -s /etc/nginx/sites-available/配置站点 /etc/nginx/sites-enabled/

步骤就四步:先在 sites-available 编写配置文件,然后 nginx -t 测试,再创建软链接到 sites-enabled,最后重载 nginx -s reload。

站点配置文件 /etc/nginx/sites-enabled/default

server {
        listen 8080 default_server;
        listen [::]:8080 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;
        # 这里写入了绝对路径,如果是 root html就是相对路径,相对在nginx安装目录下的html
        # 使用apt默认安装就是这个路径

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;
        # 访问该路径没有页面就默认展示上面的页面

        server_name _;
        # 下面可以写server、location代码块
# 域名/主机配置,下面可以分多个location
        location / {
        # 域名后面跟着的目录/路径,即URI/uri
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}

下面单独列出 error_page 的参数配置,表示访问错误页面返回的结果:

server {
    listen 8080;
    root /var/www/html;
    server_name _;
    
    # 加这三行
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    
    location / {
        try_files $uri $uri/ =404;
    }
}