About Nginx's architecture

Source: Internet
Author: User
Tags lua

nginx-Architecture Chapter

First, Nginx frequently asked questions

1. Same server_name multiple virtual host priority access

# three config files: # testserver1:server_name testserver1 www.rona1do.top;root/opt/app/code1;# testserver2:server_name Testserver2 www.rona1do.top;root/opt/app/code2;# testserver3:server_name Testserver3 www.rona1do.top;root/opt/app/ Code3;
configuring three virtual hosts of the same server_name above will first access the Testserver1, the priority of which is the order of the server reading, that is, the name of the file.

2. Location-matching Priority

    • =: Exact match for normal characters, i.e. exact match

    • ^~: Indicates normal character matching, using prefix matching

    • ~ ~ : Indicates the execution of a regular match (plus case insensitive)

The
above priority is lowered from top to bottom, the first two matches are exact matches, the match is no longer looking down, and the regular match matches to the corresponding string will continue to look for a more accurate match.

3. The use of Nginx try_files

Check if the file exists in order
# first check the corresponding URL address of the file does not exist, if not exist to find/index.php, similar to redirect location/{    try_file $uri/index.php;}

4. Nginx Alias and Root differences

    • Root

location/request_path/image/{    root/local_path/image/;} # Request: http://www.rona1do.top/request_path/image/cat.png# query:/local_path/image/request_path_image/cat.png
    • Alias

location/request_path/image/{    alias/local_path/image/;} # Request: http://www.rona1do.top/request_path/image/cat.png# query:/local_path/image/cat.png

5. How to pass the user's real IP address

    • In the case of an agent, REMOTE_ADDR gets the IP of the proxy, not the user's IP

    • X-forwarded-for can easily be tampered with

General Solution: can negotiate with the first level agent, set the header information X_REAL_IP record the user's IP
set x_real_ip=$remote_addr

6. Common error codes in Nginx

    • 413:request Entity too large

      • User upload file limit: client_max_body_size

    • 502:bad Gateway

      • Back-end service not responding

    • 504:gateway time-out

      • Back-end service timed out

Second, Nginx performance optimization

1. Performance Optimization Considerations

    • Current system structure bottlenecks

      • Observation indicators (top view status, logs, etc.), stress testing

    • Understanding Business Models

      • Interface service type, hierarchical structure of the system

    • Performance and safety

      • Configuring firewalls that are too focused on security can degrade performance

2. AB Interface pressure test tool

    1. Installation

      • yum install httpd-tools

    2. Use

      • Ab-n 2000-c 2 HTTP://127.0.0.1/

      • -N: Total number of requests

      • -C: Concurrency number

      • -K: Whether to turn on long connections

3. System and Nginx performance optimization

    1. File handle

      • Linuxunix files together, the file handle is an index

    2. Setup mode

      -System global modification, user local modification, process local modification
system global Modification and user local modification:
configuration file: /etc/security/limits.conf
# Root:root User root soft nofile 65535# hard force limit, soft more than will send reminders (mail, etc.), do not limit the root of the Nofile 65535# *: All users *     soft nofile 65535* Hard     Nofile 65535
Process Locality Modification
configuration file: /etc/nginx/nginx.conf
# set Worker_rlimit_nofile 35535 for Nginx process;

4. CPU Affinity

CPU Affinity: The most intuitive benefit of binding a process/thread to the CPU is to increase the hit rate of the CPU cache, thus reducing memory access loss and increasing the speed of the program.
    • Number of physical CPUs:cat /proc/cpuinfo | grep "physical id" | sort | uniq | wc -l

    • CPU Core:cat /proc/cpuinfo | grep "cpu cores" | uniq

    • Core and process usage: Press first top , then1

#/etc/nginx/nginx.conf# Nginx recommended number is consistent with CPU core number worker_processes 2;# configuring CPU affinity worker_cpu_affinity 0000000000000001 0000000000000010# equivalent to the previous line, automatically corresponds to (Nginx1.9 version above) Worker_cpu_affinity Auto

To view Nginx CPU bindings:
ps -eo pid,args,psr | grep [n]ginx

5. Nginx General Configuration Optimization

# Nginx Service using Nginx User (preferably not the root user) the user nginx;# CPU affinity (preferably in accordance with the core number) Worker_processes 2;worker_cpu_affinity auto;# The log level of error is set to Warnerror_log/var/log/nginx/error.log warn;    pid/var/run/nginx.pid;# file handle for inter-process restrictions (1w or more recommended) Worker_rlimit_nofile 35535;# event Drive Events {use Epoll; # limit how many connections each worker_processes process can handle worker_connections 10240;}    HTTP {include/etc/nginx/mime.types;        Default_type Application/octet-stream;        #字符集 (The message character set sent by the service side response) CharSet utf-8; 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/var/log/nginx/access.log main;    # Static resource processing sendfile on;    #tcp_nopush on;    Keepalive_timeout 65;    # gzip compression (for IE6 or the following versions for GZIP compression support is not very good) gzip on;    # IE6 or below do not compress (compatible) gzip_disable "MSIE [1-6]\."];        Gzip_http_version 1.1; Include/etc/nginx/conf.d/*.coNF;} 

Third, Nginx security

1. Common Malicious behavior

    • Reptile behavior and malicious crawling, resource misappropriation

      • Basic anti-theft chain function, do not allow malicious users to easily crawl the site external data

      • Secure_link_module, for data security to improve encryption verification and effectiveness, suitable for such as core important data

      • Acces_module, providing IP prevention and control of data in the background and part of User Services

2. Common means of attack

    • Background password Vault, through guessing the password dictionary constantly try to login to the background system, get the background login password

      • Background Login Password Complexity

      • Access_module, providing IP control in the background

      • Early warning mechanism (an IP that repeats requests over time, etc.)

3. File Upload Vulnerability

use some interfaces that can be uploaded to inject malicious code into the server and then access it through a URL to execute code
    • Example: Http://www.rona1do.top/upload ... (Nginx will execute 1.jpg as PHP code)

# File Upload Vulnerability Resolution location ^~/upload {    root/opt/app/images;    if ($request _file ~* (. *) \.php) {        return 403;    }}

4. SQL injection

use a non-filtered/non-audited user input attack method to let the app run SQL code that should not run
    • Nginx+lua Configuring a WAF firewall to prevent SQL injection

    • NGX_LUA_WAF Download Address

To use the WAF steps:

    1. git clone https://github.com/loveshell/ngx_lua_waf.git

    2. cd ngx_lua_waf

    3. mv ngx_lua_waf /etc/nginx/waf

    4. vim /etc/nginx/waf/conf.lua, modify the Rulepath to the corresponding path (/etc/nginx/waf/wafconf)

    5. vim /etc/nginx/waf/wafconf/post, add a row, \sor\s+ and put the regular SQL injection

    6. Integrated WAF:

#/etc/nginx/nginx.conflua_package_path "/etc/nginx/waf/? Lua "; lua_shared_dict limit 10m;init_by_lua_file/etc/nginx/waf/init.lua;access_by_lua_file/etc/nginx/waf/waf.lua
    1. Reload Nginx

5. The CC attack in a complex access attack

    • waf/conf.luaOpen the anti-CC attack configuration item in the configuration file

      • CCDeny="on"

      • CCrate="100/60" #每60秒100次请求

Iv. Summary of Nginx

    1. Define Nginx's role in the service system

      • Static resource Service

      • Proxy service

      • Static separation

    2. Design evaluation

      • LVS, KeepAlive, sys Log, Fastcgi

      • User rights, log directory hold

      • CPU, memory, hard disk

      • Hardware

      • System

      • Associated services

    3. Configuration Considerations

      • Reasonable configuration

      • Understanding the principle (HTTP, operating system ...

      • Follow the log

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.