기술나눔

[Linux 보안 운영 및 유지보수] Nginx 관련

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Nginx 관련

1. 개요

Nginx는 높은 동시성 및 높은 로드 기능을 갖춘 웹 서버이며 다음과 같은 장점이 있습니다.

  1. 안정적이고 시스템 리소스와 메모리를 덜 차지합니다.
  2. 소프트웨어 설치 패키지는 크기가 작고 사용자 정의가 가능합니다.
  3. 높은 동시성 기능을 갖추고 있으며 30,000~50,000개의 요청을 처리할 수 있습니다.

Nginx는 정적 페이지를 위한 웹 서버로서 주로 성능을 고려하고 효율성에 큰 관심을 기울입니다.

구성 파일(가장 기본적인 구성 파일):

구성 파일은 주로 전역 블록, 이벤트 블록 및 http 블록의 세 가지 블록으로 나뉩니다.

# 全局块
worker_processes  1;  
# 事件区块
events {
    worker_connections  1024;
}
# http区块
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost; #改为IP地址
        # 反向代理
        location / {
            root   html; #存放目录
            index  index.html index.htm;
        }
        # 错误页面路由
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

글로벌 블록: 관련 프로세스 번호, 프로세스 ID, 저장 경로, 로그 저장 경로, 사용자 그룹 및 기타 정보를 포함하여 niginx 서버의 전체 구성을 저장하는 데 사용됩니다.

이벤트 블록: niginx 서버 및 사용자 연결과 관련된 구성을 저장하는 데 사용됩니다.

http 블록: http 글로벌 블록 및 서버 블록을 포함하여 일부 서버 액세스 제어 및 타사 구성을 저장하는 데 사용됩니다.

2. 역방향 프록시

2.1 역방향 프록시 관련

클라이언트가 액세스할 때 액세스하는 데 구성이 필요하지 않습니다. 역방향 프록시 서버는 클라이언트의 요청을 수신하고 역방향 프록시 서버는 액세스를 선택하고 얻은 데이터를 클라이언트에 반환합니다.이것의 장점은 역방향 프록시 서버를 사용하면실제 서버 IP는 숨기고 프록시 서버 IP는 노출

구성 파일:

#接口端
location /police/ {
    proxy_pass   http://192.168.1.1:8852/police/;
    proxy_redirect default;
    proxy_http_version 1.1;
    proxy_connect_timeout   60;
    proxy_send_timeout      60;
    proxy_read_timeout      90;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

/police 요청으로 시작하는 인터페이스가 나타나면 http://192.168.1.1:8852/police/에 액세스하세요.

여러 포트에 대한 역방향 프록시를 정의하려면 프록시 헤더(위치 /police/)와 액세스된 IP 주소(proxy_pass http://192.168.1.1:8852/police/;)를 수정해야 합니다.

2.2 순방향 프록시

근거리 통신망 사용자가 인터넷에 접속하고 프록시 서버를 통해 서버에 접속하려면 순방향 프록시 서버가 필요합니다.

3. 로드 밸런싱

요청을 단일 서버로 전송하는 방식에서 여러 서버로 전송하는 방식으로 변경하여 로드 밸런싱을 달성합니다.

#动态服务器组
upstream dynamic_zuoyu {
    server localhost:8080;  #tomcat 7.0
    server localhost:8081;  #tomcat 8.0
    server localhost:8082;  #tomcat 8.5
    server localhost:8083;  #tomcat 9.0
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

로드 밸런싱을 달성하는 기본 방법에는 폴링 방법, 가중치 가중치 모드, ip_hash, 최소_conn의 네 가지가 있습니다.

방법설명하다
폴링 방법기본 모드
무게 무게무게에 따라 배분
ip_해시IP를 기준으로 할당됨
최소_연결최소 연결 시간을 기준으로 할당

3.1 구현 방법

  1. 폴링 방법(기본값):

    각 요청은 시간순으로 하나씩 각 서버에 할당됩니다.

    #动态服务器组
    upstream dynamic_zuoyu {
        server localhost:8080;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083;  #tomcat 9.0
        	# server 参数
        	#fail_timeout 最大失败时间
        	#max_fails	设置在fail_timeout参数设置的时间内最大失败次数,超过则认为停机
        	#fail_time	服务器会被认为停机的时间长度,默认为10s
        	#backup	标记该服务器为备用服务器,当主服务器停止时,请求会被发送到它这里
        	#down	标记服务器永久停机
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  2. 가중치 가중치(가중 폴링):

    폴링 확률을 지정하고, 가중치의 가중치를 통해 액세스를 제어합니다. 액세스 비율은 가중치에 비례합니다.

    #动态服务器组
    upstream dynamic_zuoyu {
        server localhost:8080   weight=2;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082   backup;  #tomcat 8.5
        server localhost:8083   max_fails=3 fail_timeout=20s;  #tomcat 9.0
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  3. ip_hash:

    요청은 해시 알고리즘을 통해 처리되며, 사용자가 다시 서버에 접속하면 자동으로 위치를 찾아냅니다. 각 요청은 액세스 IP의 해시 결과에 따라 할당되므로 각 사용자는 백엔드 서버에 고정적으로 액세스할 수 있습니다. .

    #动态服务器组
    upstream dynamic_zuoyu {
        ip_hash;    #保证每个访客固定访问一个后端服务器
        server localhost:8080   weight=2;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083   max_fails=3 fail_timeout=20s;  #tomcat 9.0
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  4. 최소 연결:

    연결 수가 적은 백엔드 서버로 요청을 전달합니다.

    #动态服务器组
    upstream dynamic_zuoyu {
        least_conn;    #把请求转发给连接数较少的后端服务器
        server localhost:8080   weight=2;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082 backup;  #tomcat 8.5
        server localhost:8083   max_fails=3	fail_timeout=20s;  #tomcat 9.0
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

4. 움직임과 정적의 분리

동적 페이지와 정적 페이지는 서로 다른 서버에서 구문 분석됩니다.

구성 파일:

#访问静态资源服务器
location /image/ {
  root   /var/filecenter/;
}
location /static/ {
  root   /var/filecenter/;
}
location /car/ {
  root   /var/filecenter/;
}
location ~ .*.(html|htm|gif|jpg|jpeg|bmp|png|ico|js|css)$ {
  root /Users/dalaoyang/Downloads/static;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
#动态页面访问后台服务
#接口端
        location /police/ {
            proxy_pass   http://192.168.1.1:8852/police/;
            proxy_redirect default;
            proxy_http_version 1.1;
            proxy_connect_timeout   60;
            proxy_send_timeout      60;
            proxy_read_timeout      90;
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5. 공통 명령

yum install nginx	安装nginx
netstat -anput|grep nginx 查看nginx进程
netstat -nltp	查看服务器端口占用情况
cd /usr/local/nginx/sbin/
./nginx  启动
./nginx -s stop  停止
./nginx -s quit  安全退出
./nginx -s reload  重新加载配置文件  如果我们修改了配置文件,就需要重新加载。
ps aux|grep nginx  查看nginx进程
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

6. 전체 구성 파일


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ .php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

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


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119