Table of Contents
Hide nginx version number
View version number
Hide version information
Modify users and groups
Cache time
Log segmentation
Configure Nginx to implement connection timeout
更改Nginx运行进程数
配置Nginx实现网页优化压缩功能
压缩功能参数
配置防盗链
Additional interview questions: Which nginx modules have been used and what optimizations have been done
Home Operation and Maintenance Nginx Example analysis of Nginx anti-hotlink and service optimization configuration

Example analysis of Nginx anti-hotlink and service optimization configuration

May 15, 2023 am 10:31 AM
nginx

      Hide nginx version number

      View version number

      Method 1: curl Command

      You can use the command curl -I http://192.168.80.130 in CentOS to display the response message header information.

      curl -I http://192.168.80.130

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Method 2: View

      on the web page

      1. #Switch to the html directory and drag an image into it
      cd /usr/local/nginx/html

      2. #View on the webpage
      http://192.168.59.118 /game.png

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Hide version information

      Method 1: Modify the configuration file

      1.#修改配置文件
      vim /usr/local/nginx/conf/nginx.conf
       
          ```handlebars
      http {
          include       mime.types;
          default_type  application/octet-stream;
          server_tokens off;                        #添加,关闭版本号
          ......
      }
       
      2.#重启nginx
      systemctl restart nginx
       
      3.#查看版本是否被隐藏
      curl -I http://192.168.80.130
      Copy after login

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Method 2: Modify the source code file, recompile and install

      You can customize the version number, which can be confusing

      1. #切换至nginx安装包所在目录
      cd /opt/
      2. #停止nginx服务
      systemctl stop nginx.service
      3. #切换至安装目录
      cd nginx-1.12.0/
      4. #切换至内核目录
      cd src/core/
      5. #进入配置文件
      vim nginx.h
      
      #define NGINX_VERSION      "老铁"
      #define NGINX_VER          "666/" NGINX_VERSION
      
      6. #切换至文件目录
      cd ../../
      
      7. #编译
      ./configure \
      --prefix=/usr/local/nginx \
      --user=nginx \
      --group=nginx \
      --with-http_stub_status_module
      
      8. #安装
      make && make install -j4
      
      9. #将配置文件下的之前关闭版本信息开启
      vim /usr/local/nginx/conf/nginx.conf
      server_tokens on;
      
      10. #重启nginx
      systemctl restart nginx
      
      11. #查看版本信息
      curl -I http://192.168.59.118
      Copy after login

      Modify users and groups

      1. #修改配置文件
      vim /usr/local/nginx/conf/nginx.conf
      
      user  dayu dayu; #取消注释,修改用户为 dayu ,组为 dayu
      
      2. #创建非登录用户
      useradd -s /sbin/nologin dayu
      
      3. #重启服务
      systemctl restart nginx
      
      4. #查看是否修改成功
      ps aux | grep nginx
      Copy after login

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Cache time

      When nginx returns the web page data to the client Finally, the cache time can be set to facilitate direct return when requesting the same content in the future, avoiding repeated requests and speeding up access. Generally, the cache time is set for static web pages, and no cache time is set for dynamic web pages.

      1. #修改配置文件
      vim /usr/local/nginx/conf/nginx.conf
              #添加以下内容
              location ~ \.(jpg|png|bmp|gif)$ {
                  root   html;
                  expires 1d;
              }
      
      
      2. #查看是否有语法错误
      nginx -t
      
      3. #重启服务
      systemctl restart nginx.service 
      
      4.#在网页中查看服务
      http://192.168.80.130/good.jpg
      
       Cahce-Control:max-age=86400 表示缓存时间是 86400 秒。
      也就是缓存一天的时间,一天之内浏览器访问这个页面,都是用缓存中的数据,
      而不需要向 Nginx 服务器重新发出请求,减少了服务器的使用带宽。
      Copy after login

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Log segmentation

      As the running time of Nginx increases, the logs generated will gradually increase. In order to To easily grasp the running status of Nginx, you need to always pay attention to the Nginx log file. Log files that are too large are a disaster for monitoring and are inconvenient for analysis and troubleshooting. Log files need to be cut regularly.

      1. #写脚本
      vim /usr/local/nginx/nginx_log.sh 
      
      #!/bin/bash
      #this is for divide nginx log
      d=$(date +%F -d -1day)                                       #显示前一天的时间
      path="/var/log/nginx"   
      pid="/usr/local/nginx/logs/nginx.pid"
      
      [ -d $path ] ||mkdir -p $path                                #创建日志文件目录
      mv /usr/local/nginx/logs/access.log ${path}/www.yxp.com-$d   #移动并重命名日志文件
      kill -USR1 $(cat $pid)                                       #重建新日志文件
      find $path -mtime +30 -delete                                #删除30天之前的日志文件
      
      2. #赋予权限
      chmod +x /usr/local/nginx/nginx_log.sh 
      
      3. #计划任务
      [root@localhost nginx]#crontab -e
      
      30 1 * * * /usr/local/nginx/nginx_log.sh
      Copy after login

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Configure Nginx to implement connection timeout

      HTTP has a KeepAlive mode , which tells the web server to keep the TCP connection open after processing a request. If other requests from the same client are received, the server will use this unclosed connection without establishing another connection.

      KeepAlive remains open for a period of time, and they will occupy resources during this time. Taking up too much will affect performance.

      vim /usr/ local/nginx/conf/nginx. conf
      http {
      ......
      keepalive_ timeout 65 180;
      client header timeout 80;
      client_ body_ timeout 80;
      ......
      }
      systemctl restart nginx
      Copy after login

      keepalive_ timeout

      • Specify the KeepAlive timeout (timeout). Specify the maximum length of time each TCP connection can be maintained, after which the server will close the connection.

      • The default value of Nginx is 65 seconds. Some browsers only maintain a maximum of 60 seconds, so it can be set to 60 seconds. If it is set to 0, keepalive connections are disabled.

      • The second parameter (optional) specifies the time value in the response header Keep-Alive: timeout=t ime. This header allows some browsers to actively close the connection, so that the server does not have to close the connection. Without this parameter, Nginx will not send the Keep-Alive response header.

      client_ header_ timeout

      The timeout period for the client to send a complete request header to the server. If the client does not send a complete request header within the specified time, Nginx returns HTTP 408 (Request Timed Out).

      client_ body_ timeout

      Specify the timeout for sending requestbody after the client establishes a connection with the server. If the client does not send anything within the specified time, Nginx returns HTTP 408 (Request Timed Out).

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      更改Nginx运行进程数

      在高并发场景,需要启动更多的Nginx进程以保证快速响应,以处理用户的请求,避免造成阻塞

      更改进程数的配置方法

      修改配置文件,修改进程配置参数

      修改配置文件的worker_processes参数

      • 一般设为CPU的个数或者核数

      • 在高并发的情况下可设置为CPU个数或者核数的2倍

      增加进程数,可减少系统的开销,提升服务速度

      使用ps aux查看运行进程数的变化情况

      [root@www conf]# cat /proc/cpuinfo | grep -c "physical"
      4
      [root@www conf]# vi nginx.conf
      worker_ processes 4;
      [root@www conf]# systemctl restart nginx
      [root@www conf]# ps aux | grep nginx
      Copy after login

      默认情况,Nginx的多个进程可能跑在一 个CPU上,可以分配不同的进程给不同的CPU处理,充分利用硬件多核多CPU。
      在一台4核物理服务器,进行配置,将进程进行分配。

      [root@www conf]# vi nginx.conf
      worker_ processes 4;
      worker_ cpu_ affinity 0001 0010 0100 1000;
       
      1代表CPU的位置
      Copy after login

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      配置Nginx实现网页优化压缩功能

      • Nginx的ngx_http_ gzip_module压缩模块提供对文件内容压缩的功能

      • 允许Nginx服务器将输出内容在发送客户端之前进行压缩,以节约网站带宽,提升用户的访问体验,默认已经安装

      • 可在配置文件中加入相应的压缩功能参数对压缩性能进行优化

      压缩功能参数

      1. #修改配置文件
         gzip on;                          #取消注释,开启gzip压缩功能
         gzip_min_length 1k;              #最小压缩文件大小
         gzip_buffers 4 16k;              #压缩缓冲区,大小为4个16k缓冲区
         gzip_http_version 1.1;           #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
         gzip_comp_level 6;               #压缩比率
         gzip_vary on;                    #支持前端缓存服务器存储压缩页面
         gzip_types text/plain text/javascript application/x-javascript text/css text/xml application/xml application/xml+rss image/jpg image/jpeg image/png image/gif application/x-httpd-php application/javascript application/json;       #压缩类型,表示哪些网页文档启用压缩功能
      
      2. #重启服务
      systemctl restart nginx.service 
      
      
      3. #网页查看
      http://192.168.59.118/game.png
      Copy after login

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      配置防盗链

      在企业网站服务中,一般都要配置防盗链功能,以避免网站内容被非法盗用,造成经济损失,也避免了不必要的带宽浪费。

      Nginx 的防盗链功能也非常强大,在默认情况下,只需要进行很简单的配置,即可实现防盗链处理。

      vim /usr/ local/nginx/conf/nginx. conf
      http {
      ......
         server {
           ......
       
          location ~* \. (jpglgiflswf)$ {
       
            valid_ referers none blocked * . kgc. com kgc . com;
       
              if ( $invalid referer ) {
       
              rewrite ^/ http: I /www. kgc. com/error。pngi
       
                 #return 403;
       
               }
       
            }
       
        ......
       
         }
      }
      Copy after login

      ~* \. (jpgIgifIswf)$ :这段正则表达式表示匹配不区分大小写,以.jpg或.gif 或.swf结尾的文件:
       
      valid_ referers :设置信任的网站,可以正常使用图片:
       
      none:允许没有http_refer的请求访问资源(根据Referer的定义,它的作用是指示一个请求是从哪里链接过来的,如果直接在浏览器的地址栏中输入一个资源的URL地址,那么这种请求是不会包含Referer 字段的),如http:/ /www.dayu.com/ game.jpg
       
      我们使用http://www. dayu.com访问显示的图片,可以理解成http://www. dayu.com/game.jpg这个请求是从http://www. dayu.com这个链接过来的。
       
      blocked: 允许不是http://开头的, 不带协议的请求访问资源;
       
      *. dayu. com: 只允许来自指定域名的请求访问资源,如http://www. dayu.com
       
      if语句:如果链接的来源域名不在valid_ referers所列出的列表中,$invalid_ referer为true, 则执行后面的操作,即进行重写或返回403 页面。

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      第二台机器配置内容:

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Example analysis of Nginx anti-hotlink and service optimization configuration

       现在还是可以正常显示的

      Example analysis of Nginx anti-hotlink and service optimization configuration

      Now the anti-theft picture appears

      Additional interview questions: Which nginx modules have been used and what optimizations have been done

      gzip
      Website data compression
      rewrite
      Address rewriting
      stub_ status
      Statistical nginx service status
      ssl supports https,
      You must first use openss1 or TLS tools to generate relevant certificates and private key files . Then call the certificate and private key in the ssl module configuration
      upstream
      Use nginx as a reverse proxy web cluster and define the cluster server pool
      stream
      Used to define a 4-layer reverse proxy

      auth_ basic
      User authentication###fastcgi ### Forward the request to php###--with-module name ### Enable the module###--without-module name ### Disable the module### # ##Hidden version number, compression, caching, anti-leeching, continuous maintenance, optimizing the number of working processes and process connections, log segmentation, reverse proxy ######

      The above is the detailed content of Example analysis of Nginx anti-hotlink and service optimization configuration. For more information, please follow other related articles on the PHP Chinese website!

      Statement of this Website
      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

      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

      Notepad++7.3.1

      Notepad++7.3.1

      Easy-to-use and free code editor

      SublimeText3 Chinese version

      SublimeText3 Chinese version

      Chinese version, very easy to use

      Zend Studio 13.0.1

      Zend Studio 13.0.1

      Powerful PHP integrated development environment

      Dreamweaver CS6

      Dreamweaver CS6

      Visual web development tools

      SublimeText3 Mac version

      SublimeText3 Mac version

      God-level code editing software (SublimeText3)

      How to configure cloud server domain name in nginx How to configure cloud server domain name in nginx Apr 14, 2025 pm 12:18 PM

      How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

      How to start nginx server How to start nginx server Apr 14, 2025 pm 12:27 PM

      Starting an Nginx server requires different steps according to different operating systems: Linux/Unix system: Install the Nginx package (for example, using apt-get or yum). Use systemctl to start an Nginx service (for example, sudo systemctl start nginx). Windows system: Download and install Windows binary files. Start Nginx using the nginx.exe executable (for example, nginx.exe -c conf\nginx.conf). No matter which operating system you use, you can access the server IP

      How to check nginx version How to check nginx version Apr 14, 2025 am 11:57 AM

      The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

      How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

      You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

      How to run nginx apache How to run nginx apache Apr 14, 2025 pm 12:33 PM

      To get Nginx to run Apache, you need to: 1. Install Nginx and Apache; 2. Configure the Nginx agent; 3. Start Nginx and Apache; 4. Test the configuration to ensure that you can see Apache content after accessing the domain name. In addition, you need to pay attention to other matters such as port number matching, virtual host configuration, and SSL/TLS settings.

      How to check whether nginx is started How to check whether nginx is started Apr 14, 2025 pm 01:03 PM

      How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

      How to create a mirror in docker How to create a mirror in docker Apr 15, 2025 am 11:27 AM

      Steps to create a Docker image: Write a Dockerfile that contains the build instructions. Build the image in the terminal, using the docker build command. Tag the image and assign names and tags using the docker tag command.

      How to start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

      Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

      See all articles