Nginx 的安装与使用(入门教程)


前言

生命不息,学习不止~~

对于小白而言 狂神说-Nginx详解 这个教程算是比较清晰易懂了,可点击链接去看视频,以下内容至少我对该教程进行简单的整理,方便以后回顾。


一、概述

官网:http://nginx.org/en/

Nginx (engine x)是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的 Rambler.ru 站点(俄文:Рамблер)开发的,公开版本1.19.6发布于2020年12月15日。

它具有很多非常优越的特性:

  • 占有内存少
  • 并发能力强,能够支持高达 50,000 个并发连接数的响应
  • 由 C 语言编写,可移植性强
  • 安装非常的简单、配置文件非常简洁(还能够支持perl语法)、Bug非常少的服务

作用:

  • 正向代理:意思是一个位于客户端和原始服务器(origin server)之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器),然后代理向原始服务器转交请求并将获得的内容返回给客户端。客户端才能使用正向代理。当你需要把你的服务器作为代理服务器的时候,可以用Nginx来实现正向代理。
  • 反向代理:是指以代理服务器来接受 客户端的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给客户端,此时代理服务器对外就表现为一个反向代理服务器。
  • 动静分离:在我们的软件开发中,有些请求是需要后台处理的,有些请求是不需要经过后台处理的(如:css、html、jpg、js等等文件),这些不需要经过后台处理的文件称为静态文件。让动态网站里的动态网页根据一定规则把不变的资源和经常变的资源区分开来,动静资源做好了拆分以后,我们就可以根据静态资源的特点将其做缓存操作。提高资源响应的速度。
  • 负载均衡:负载均衡也是Nginx常用的一个功能,负载均衡其意思就是分摊到多个操作单元上进行执行。简单而言就是当有2台或以上服务器时,根据规则随机的将请求分发到指定的服务器上处理,负载均衡配置一般都需要同时配置反向代理,通过反向代理跳转到负载均衡。而Nginx目前支持自带3种负载均衡策略,还有2种常用的第三方策略。

二、下载与安装

下载链接:http://nginx.org/en/download.html

1. windows

下载 windows 版的 Nginx 压缩包

在这里插入图片描述

下载成功之后,将安装包放在 非中文 目录下,解压即可:

在这里插入图片描述

进入解压好的文件夹中,双击运行 nginx.exe

在这里插入图片描述

或者使用 dos 命令 nginx.exe 启动 nginx

在这里插入图片描述

游览器输入:localhost 或者 localhost:80,看到以下页面说明 nginx 启动成功

在这里插入图片描述


2. linux

下载 Linux 版的 Nginx 压缩包

在这里插入图片描述

下载完成

在这里插入图片描述

先在 Linux 服务器上添加 /soft/nginx 目录来存放 nginx 的安装包,并且进入到该目录下

mkdir /soft/nginx
cd /soft/nginx

在这里插入图片描述

将下载好的压缩包使用 rz 命令上传到 Linux 服务器上

在这里插入图片描述

解压 nginx 压缩包

tar -zxvf nginx-1.22.0.tar.gz

在这里插入图片描述

进入解压后生成的目录文件

cd nginx-1.22.0/

在这里插入图片描述

配置configure:需要配置—prefix=/usr/local/nginx 否则会出错误

./configure --prefix=/usr/local/nginx

在这里插入图片描述

执行 make

make

在这里插入图片描述

执行 make install

make install

在这里插入图片描述

查看安装编译目录

whereis nginx

在这里插入图片描述

进入到编译目录的 sbin 目录下,启动 nginx

# 进入 sbin目录下
cd /usr/local/nginx/sbin
# 启动 nginx
./nginx

在这里插入图片描述

查看 nginx 进程

ps aux|grep nginx

在这里插入图片描述

可以看到 nginx 已经启动了完成了,接下来测试一下,输入你 Linux 服务器的地址:比如 192.168.12.45 或者 192.168.12.45:80,进行访问,如果能看到以下页面就表示 nginx 安装成功。

在这里插入图片描述

PS:在没有修改 nginx 默认的配置文件(nginx.conf)下,如果输入 IP 地址 没有出现以上页面的话,请检查服务防火墙是否关闭,或者是 80 端口是否对外开发,如果使用的服务器是云服务器,还需要检查云服务器是开发对应的 80 端口。

如果是在虚拟机上,建议关闭防火墙

# 关闭防火墙
systemctl stop firewalld.service 
# 查看防火墙的状态
firewall-cmd --state 
# 禁止firewall开机启动
systemctl disable firewalld.service

或者为了安全,只开放特定的端口号,nginx 默认监听的端口是 80

# 关闭防火墙
systemctl stop firewalld.service 
# 3306 端口对外开放
firewall-cmd --remove-port=80/tcp --permanent 
# 重启防火墙
firewall-cmd --reload

三、配置文件说明

nginx 的配置文件是 conf 目录下的 nginx.conf

在这里插入图片描述

查看该文件,虽然看到其中的配置是比较多的,其实大概就分为这么几块内容

在这里插入图片描述

(1)全局块

主要设置一些影响nginx 服务器整体运行的配置指令。如:用户(组),生成worker process 数,日志存放路径,配置文件引入,pid文件路径。

(2)events 块

影响nginx 服务器与用户的网络连接。如:每个worker processs 的最大连接数,事件驱动模型。

(3)http 块

nginx 配置中的重要部分,代理,缓存等功能都可以在此配置。如:文件引入,mime-type 定义,连接超时,单连接请求数上限。

(4)server 块

与“虚拟主机”的概念有密切关系。每个server 块相当于一台虚拟主机,最常见的两个配置项是监听配置和虚拟主机的名称或IP配置。

(5)location 块

在server 块中,可以有多个。地址定向,数据缓存,和应答控制等功能都是在这部分实现。

nginx.conf配置文件(转载于:https://my.oschina.net/u/2552286/blog/3056865

# =========================全局块============================
# user user [grop];        # 指定可以运行nginx 服务器的用户及组。只被设置的用户及组才有权限管理
# user nobody nobody;      # 所用用户可用,默认配置
user nginx nginx; 
# worker_processes number | auto;   # 控制并发处理,值越大,支持的并发数越多
# worker_processes 1;               # 默认值 ,最多产生1个worker_processes
worker_processes auto;
# pid file;                  # pid 存放路径.相对或绝对路径
# pid logs/nginx.pid;        # 默认在安装目录logs/nginx.pid
pid /var/run/nginx.pid;
# error_log file | stder [debug | info | notice | warn | error | crit | alert | emerg];  #错误日志存放路径
# error_log logs/error.log error;  # 可在 全局块,http 块 ,serveer 块,location 块中配置
error_log /data/wwwlogs/error_nginx.log crit;
# include file;      # 配置文件引入,可以是相对/绝对路径。指令可以放在配置文件的任意地方(任意块中)
worker_rlimit_nofile 51200;
# ===========================events 块===============================
events {
    
    
    #accept_mutex on|off;      # 网络连接序列化。解决“惊群”问题
    accept_mutex on;           # 默认为开启状态
    #multi_accept on|off;      # 是否允许worker process同时接收多个网络连接,
    multi_accept off;          # 默认为关闭
    #use method;               # 事件驱动模型选择,select 、 poll 、 kqueue 、 epoll 、 rtsig 、 /dev/poll 、 eventport
    use epoll;
    #worker_connections number; # worker process 的最大连接数。 
    worker_connections 512;     # 默认值为512。注意设置不能大于操作系统支持打开的最大文件句柄数量。
}
# ==========================http块============================
http {
    
    
    # 定义 mime-type (网络资源的媒体类型)。  指定能识别前端请求的资源类型 
    include mime.types;   # 引入外部文件 ,在外部文件中有定义types 块
    default_type application/octet-stream;   # 默认为 text/plain 。 http块、server块、location块中可配置
    # access_log path [format[buffer=size]];  # 定义服务日志,记录前端的请求日志
    # access_log logs/access.log combined;    # combined 是默认定义的日志格式字符串名称
    access_log off;                          # 关闭日志
    # log_format name stirng      # 定义了日志格式,以便access_log 使用
    # log_format  combined  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    # sendfile on|off;       # 配置允许 sendfile 方式传输文件
    sendfile off;           # 默认关闭,可在http块、server块、location块 中定义
    # sendfile_max_chunk size;    # 配置worker process 每次调用sendfile()传输的数据最最大值
    # sendfile_max_chunk 0;        # 默认为0 不限制。  可在http块、server块、location块 中定义
    sendfile_max_chunk 128k;
    # keepalive_timeout timeout [header_timeout];    # 配置连接超时时间, 可在http块、server块、location块 中定义
    # keepalive_timeout 75s;        # 默认为75秒,与用户建立会话连接后,nginx 服务器可以保持这些连接打开的时间。
    keepalive_timeout 120 100s;    # 在服务器端保持连接的时间设置为120s,发给用户端的应答报文头部中keep-alive 域的设置为100s
    # keepalive_requests number;    # 单连接请求数上限
    keepalive_requests 100;        # 默认为 100
    server_names_hash_bucket_size 128;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 1024m;
    tcp_nopush on;
    server_tokens off;
    tcp_nodelay on;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    #Gzip Compression
    gzip on;
    gzip_buffers 16 8k;
    gzip_comp_level 6;
    gzip_http_version 1.1;
    gzip_min_length 256;
    gzip_proxied any;
    gzip_vary on;
    gzip_types
        text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml
        text/javascript application/javascript application/x-javascript
        text/x-json application/json application/x-web-app-manifest+json
        text/css text/plain text/x-component
        font/opentype application/x-font-ttf application/vnd.ms-fontobject
        image/x-icon;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";
    # If you have a lot of static files to serve through Nginx then caching of the files' metadata (not the actual files' contents) can save some latency.
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
######################## default ############################
#    server {
    
    
#    listen 8067;
#    server_name _;
#    access_log /data/wwwlogs/access_nginx.log combined;
#    root /data/wwwroot/default;
#    index index.html index.htm index.jsp;
#    location /nginx_status {
    
    
#        stub_status on;
#        access_log off;
#        allow 127.0.0.1;
#        deny all;
#        }
#    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
    
    
#        expires 30d;
#        access_log off;
#        }
#    location ~ .*\.(js|css)?$ {
    
    
#        expires 7d;
#        access_log off;
#        }
#    location ~ {
    
    
#        proxy_pass http://127.0.0.1:8080;
#        include proxy.conf;
#        }
#    }
#    server{
    
    
#     listen 8087;
#    server_name _;
#     root /home/wwwroot/default;
#     location / {
    
    
#      }
#    }
    upstream backend{
    
    
      server 127.0.0.1:8080 weight=1 max_fails=2 fail_timeout=2;
      server 139.224.209.104:8080 backup;
    }
    server{
    
    
      listen 80;
      listen 443 ssl;
      server_name wmcenter.xy-asia.com;
      #ssl on;
      default_type 'text/html';
      charset utf-8;
      ssl_certificate   /usr/local/cert/1634560_wmcenter.xy-asia.com.pem;
      ssl_certificate_key  /usr/local/cert/1634560_wmcenter.xy-asia.com.key;
      ssl_session_timeout 5m;
      ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
      ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
      ssl_prefer_server_ciphers on;
      root html;
      index index.html index.htm;
      location ~ .*\.(js|css)?$
      {
    
    
         expires 1h;
         proxy_pass   http://backend;
      }
      location / {
    
    
        proxy_pass  http://backend;
    add_header backendIP $upstream_addr;
    # proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
        # 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 https;
        # proxy_redirect http://http://127.0.0.1:8080 $scheme://127.0.0.1:8080;
        # port_in_redirect on;
        # proxy_redirect     off;
        include proxy.conf;
      }
      # error_log /home/wwwlogs/xywm.log;
    }
     # 缓存配置
    proxy_temp_file_write_size 264k;
    proxy_temp_path /data/wwwlogs/nginx_temp;
    proxy_cache_path /data/wwwlogs/nginx_cache levels=1:2 keys_zone=prc:200m inactive=5d max_size=400m;
    proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie; 
########################## vhost #############################
    include vhost/*.conf;
}

四、常用命令

# 进入 nginx 的 sbin 目录下
cd /usr/local/nginx/sbin/
# 启动 nginx
./nginx
# 停止
./nginx -s stop
# 安全退出
./nginx -s quit
# 重新加载配置文件        
./nginx -s reload
# 查看nginx进程    
ps aux|grep nginx    

参考链接:

Nginx 学习:https://www.kuangstudy.com/bbs/1483987971375263745

什么是Nginx? Nginx的作用是什么?:https://blog.csdn.net/it_rookie_newbie/article/details/120504512

nginx.conf配置文件(转载于:https://my.oschina.net/u/2552286/blog/3056865

Nginx—静态资源处理:https://blog.csdn.net/m0_53157173/article/details/120935194

随笔小杂记(五)——nginx访问静态资源报错403:https://blog.csdn.net/InkBamboo920/article/details/124241030

猜你喜欢

转载自blog.csdn.net/xhmico/article/details/125866385