search
HomeBackend DevelopmentPHP TutorialAbout Nginx architecture

About Nginx architecture

May 07, 2018 am 10:51 AM
nginxaboutArchitecture

Nginx-Architecture Chapter

1. Nginx FAQ

1. Multiple virtual hosts with the same server_name have priority access

# 三个配置文件:

# 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;
Configure the three virtual hosts with the same server_name mentioned above The host will access testserver1 first, and the priority of access is based on the server's reading order, that is, the order of file names.

2. Location matching priority

  • =: Exact matching of ordinary characters, that is, complete matching

  • ^~ : Indicates ordinary character matching, use prefix matching

  • ##~ ~

    : Indicates performing a regular match (adding is not case-sensitive)

The above priorities decrease from top to bottom. The first two matches are exact matches. After matching, they will no longer search downwards. If a regular match matches the corresponding string, they will continue to search downwards to see if there is more. Exact match.
3. Use of Nginx’s try_files

Check whether files exist in order
# 先检查对应的url地址下的文件存不存在,如果不存在找/index.php,类似于重定向
location / {
    try_file $uri /index.php;
}
4. The difference between Nginx’s alias and root

  • root

  • location /request_path/image/ {
        root /local_path/image/;
    }
    # 请求:http://www.rona1do.top/request_path/image/cat.png
    # 查询: /local_path/image/request_path_image/cat.png
  • alias

  • location /request_path/image/ {
        alias /local_path/image/;
    }
    # 请求:http://www.rona1do.top/request_path/image/cat.png
    # 查询: /local_path/image/cat.png
5. What method is used to pass the user’s real IP address

  • In the case of a proxy, remote_addr obtains the proxy's IP, not the user's IP

  • x-forwarded-for is easily tampered with

General solution: You can negotiate with the first-level agent and set the header information x_real_ip to 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
    • Backend service not responding
    504:gateway time-out
    • Backend service time-out
    • ## 2. Nginx performance optimization
1. Performance optimization considerations

Current system structure bottleneck
  • Observation indicators (top View status, logs, etc.), stress test
    • Understand the business model
  • Interface business type, system hierarchical structure
    • Performance and Security
  • Configuring a firewall that pays too much attention to security will reduce performance
    • 2. ab interface stress testing tool

Installation
    yum install httpd- tools
  • Use
  • ab -n 2000 -c 2 http://127.0.0.1/
    • -n: Total number of requests
    • -c: Number of concurrent requests
    • -k : Whether to enable long connections
    • 3. System and Nginx performance optimization

    File handle
    1. LinuxUnix is ​​all files, and the file handle is an index
    • Setting method
    - 系统全局性修改、用户局部性修改、进程局部性修改
  • System global modification And user locality modification:
  • Configuration file:

    /etc/security/limits.conf
    # root:root用户
    root soft nofile 65535
    # hard 强制限制、soft 超过会发送提醒(邮件等),不限制
    root hard nofile 65535
    # *:所有用户
    *     soft nofile 65535
    *     hard nofile 65535
    Process locality modification
    Configuration File:

    /etc/nginx/nginx.conf
    # 针对nginx进程进行设置
    worker_rlimit_nofile 35535;
    4. CPU affinity

    CPU affinity:

    Place the process /The most intuitive benefit of binding threads to the CPU is to increase the hit rate of the CPU cache, thereby reducing memory access losses and increasing program speed.
    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
    • top# first ##, then press
    • 1

      <pre class='brush:php;toolbar:false;'># /etc/nginx/nginx.conf # nginx建议数量跟cpu核心数保持一致 worker_processes 2; # 配置cpu亲和 worker_cpu_affinity 0000000000000001 0000000000000010 # 与上一行等价,自动对应(Nginx1.9版本以上) worker_cpu_affinity auto</pre>

      to view the cpu binding status of Nginx:

    ps -eo pid, args,psr | grep [n]ginx
    5. Nginx general configuration optimization<pre class='brush:php;toolbar:false;'># nginx服务使用nginx用户(最好不要使用root用户) user nginx; # cpu亲和(最好跟核心数保持一致) worker_processes 2; worker_cpu_affinity auto; # error的日志级别设置为warn error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; # 文件句柄对于进程间的限制(建议1w以上) worker_rlimit_nofile 35535; # 事件驱动器 events { use epoll; # 限制每一个worker_processes进程可以处理多少个连接 worker_connections 10240; } http { include /etc/nginx/mime.types; default_type application/octet-stream; #字符集(服务端响应发送的报文字符集) charset utf-8; log_format main &amp;#39;$remote_addr - $remote_user [$time_local] &quot;$request&quot; &amp;#39; &amp;#39;$status $body_bytes_sent &quot;$http_referer&quot; &amp;#39; &amp;#39;&quot;$http_user_agent&quot; &quot;$http_x_forwarded_for&quot;&amp;#39;; access_log /var/log/nginx/access.log main; # 静态资源的处理 sendfile on; #tcp_nopush on; keepalive_timeout 65; # gzip压缩(对于IE6或以下版本对于gzip压缩支持不是很好) gzip on; # IE6或以下不进行压缩(兼容) gzip_disable &quot;MSIE [1-6]\.&quot;; gzip_http_version 1.1; include /etc/nginx/conf.d/*.conf; }</pre>3. Nginx security

    1. Common malicious behaviors

    Crawling behavior and malicious grabbing and resource theft

    • Basic anti-leeching function prevents malicious users from easily crawling external data of the website
      • secure_link_module, improves encryption verification and effectiveness of data security, suitable for core important data

      • acces_module, serves the backend and some users Data provides IP prevention and control

    2. 常见的攻击手段

    • 后台密码撞库,通过猜测密码字典不断对后台系统尝试性登录,获取后台登录密码

      • 后台登录密码复杂度

      • access_module,对后台提供IP防控

      • 预警机制(一个IP在一段时间内重复不断请求等)

    3. 文件上传漏洞

    利用一些可以上传的接口将恶意代码植入到服务器中,再通过url去访问以执行代码
    • 例:http://www.rona1do.top/upload...(Nginx将1.jpg作为php代码执行)

    # 文件上传漏洞解决办法
    location ^~ /upload {
        root /opt/app/images;
        if ($request_file ~* (.*)\.php){
            return 403;
        }
    }

    4. SQL注入

    利用未过滤/未审核用户输入的攻击方法,让应用运行本不应该运行的SQL代码
    • Nginx+LUA配置WAF防火墙防止SQL注入

    About Nginx architecture

    • ngx_lua_waf 下载地址

    使用waf步骤:

    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,修改RulePath为对应路径(/etc/nginx/waf/wafconf)

    5. vim /etc/nginx/waf/wafconf/post,加入一行,\sor\s+,放sql注入的正则

    6. 集成waf:

    # /etc/nginx/nginx.conf
    lua_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. 复杂的访问攻击中CC攻击

    • waf/conf.lua配置文件中打开防cc攻击配置项

      • CCDeny="on"

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

    四、Nginx总结

    1. 定义Nginx在服务体系中的角色

    • 静态资源服务

    • About Nginx architecture

    • 代理服务

    • About Nginx architecture

    • 动静分离

  • 设计评估

    • LVS、keepalive、syslog、Fastcgi

    • 用户权限、日志目录存放

    • CPU、内存、硬盘

    • 硬件

    • 系统

    • 关联服务

  • 配置注意事项

    • 合理配置

    • 了解原理(HTTP、操作系统...)

    • 关注日志

    相关推荐:

    nginx架构与实现

    The above is the detailed content of About Nginx architecture. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

    DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

    How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

    ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

    Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

    Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

    What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

    DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

    How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

    The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

    How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

    Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

    What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

    In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

    How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

    Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!