search
HomeOperation and MaintenanceNginxAnalysis of Nginx common configuration examples

封禁 IP

通过 deny 可以封禁指定 IP

http {
    # ....
    # 封禁IP
    deny 192.168.4.3; 
    deny 31.42.145.0/24; 
    deny 51.12.35.0/24;
}

仅开放内网

需要先禁止 192.168.1.1

开放其他内网网段,然后禁止其他所有 IP

location / { 
  # block one workstation 
  deny    192.168.1.1; 
  # allow anyone in 192.168.1.0/24 
  allow   192.168.1.0/24; 
  # drop rest of the world 
  deny    all; 
}

负载均衡

需要在 nginx.conf 中配置转发服务器信息

权重: weight=1,权重如果分配的值越大,权重越高

最大连接数: max_fails=3,最多连接失败次数为3次

连接失败时间: fail_timeout=20s,每次连接失败的时间

在站点配置 default.conf 中开启负载均衡

# nginx.conf中配置转发服务器信息
upstream web {
    server 192.168.37.2 weight=1 max_fails=3 fail_timeout=20s;
    server 192.168.37.3 weight=1 max_fails=3 fail_timeout=20s;
}

# default.conf中开启负载均衡
location / {
    proxy_pass http://web/;
}

列出文件列表

有时候服务器作为资源服务器,给用户提供下载资源使用

需要将服务上的文件以目录形式列出来

可以通过配置 autoindex on 允许列出目录,启用目录流量

可以通过 autoindex_exact_size off 显示出文件的确切大小,单位是 bytes

可以通过 autoindex_localtime on 显示的文件时间为文件的服务器时间

location / {
    autoindex on;
    autoindex_exact_size on;
    autoindex_localtime on;
}

路由转发

有时候用户通过路由访问服务器的资源,其实你的资源在另一个文件夹下面

可以使用 alias 命令,将用户请求进行转发

# nginx服务器
location /static {
    alias /public;
}
 
# window服务器
location ^~ /static {
    alias "D:\\public\\静态资源";
}

开启 gzip 压缩

gzip 压缩是一种提升访问速度的优化方向,可以大大提高

http {
    # 开启gzip
    gzip on;

    # 是否在http header中添加Vary: Accept-Encoding,建议开启
    gzip_vary on;

    # 启用gzip压缩的最小文件,小于设置值的文件将不会压缩
    gzip_min_length 1k;

    gzip_proxied any;

    # gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间
    gzip_comp_level 6;

    # 设置压缩所需要的缓冲区大小
    gzip_buffers 16 8k;

    # 设置gzip的版本
    gzip_http_version 1.1;

    # 进行压缩的文件类型。javascript有多种形式,后面的图片压缩不需要的可以自行删除
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}

解决跨域

server {
    location / {
        #允许跨域请求的域,*代表所有 
        add_header 'Access-Control-Allow-Origin' *; 
        #允许带上cookie请求 
        add_header 'Access-Control-Allow-Credentials' 'true'; 
        #允许请求的方法,比如 GET / POST / PUT / DELETE 
        add_header 'Access-Control-Allow-Methods' *; 
        #允许请求的header 
        add_header 'Access-Control-Allow-Headers' *;
    }
}

资源防盗链

为了防止其他网站直接实用我方的静态资源,可以增加防盗链配置

server {
    location ~*/(js|image|css) {
        # 检测*.autofelix.cn的请求,如果检测是无效的,直接返回403
        valid_referers *.autofelix.cn; 
        if ($invalid_referer) {
            return 403;
        }
     }
}

Keepalived 提高吞吐量

通过 keepalived 可以设置长连接处理的数量

通过 proxy_http_version 可以设置长连接 http 版本

通过 proxy_set_header 可以清除 connection header 信息

# nginx.conf中配置吞吐量
upstream web {
    server 192.168.37.3 weight=1;keepalive 32;
}

# default.conf中配置
location / {
     proxy_pass http://tomcats;
     proxy_http_version 1.1;
     proxy_set_header Connection "";
}

HTTP 强制跳转 HTTPS

很多网站中,都强制实用 https 协议

这样我们就需要将 http 强制跳转到 https

server {
    # 监听的端口号
    listen 80;
    
    # 强制跳转
    rewrite ^(.*)$ https://$host$1 permanent;
}
 
server {
    # 监听的端口号
    listen       443;
    # 主机名
    server_name www.520web.cn;
    # 开启ssl验证
    ssl on;
    # 字符集
    charset utf-8;
    # 访问的根目录
    root   /var/www/html;
    # 错误页面
    error_page  404    ...404文件路径;
    
    # 图片视频静态资源缓存到客户端时间
    location ~ .*\.(jpg|jpeg|gif|png|ico|mp3|mp4|swf|flv){
      expires 10d;
    }
    
    # js/css静态资源缓存到客户端时间
    location ~ .*\.(js|css){
      expires 5d;
    }
    
    # ssl的相关配置,pem文件的地址
    ssl_certificate  ...pem文件的绝对路径;
    # key文件的绝对路径
    ssl_certificate_key  ...key文件的绝对路径;
    # 断开重连时间
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    # ssl协议
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    
    # 首页访问的文件
    location / {
        index  index.php index.html index.htm;
    }

    # php-ftm配置
    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

The above is the detailed content of Analysis of Nginx common configuration examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
The Advantages of NGINX: Speed, Efficiency, and ControlThe Advantages of NGINX: Speed, Efficiency, and ControlMay 12, 2025 am 12:13 AM

The reason why NGINX is popular is its advantages in speed, efficiency and control. 1) Speed: Adopt asynchronous and non-blocking processing, supports high concurrent connections, and has strong static file service capabilities. 2) Efficiency: Low memory usage and powerful load balancing function. 3) Control: Through flexible configuration file management behavior, modular design facilitates expansion.

NGINX vs. Apache: Community, Support, and ResourcesNGINX vs. Apache: Community, Support, and ResourcesMay 11, 2025 am 12:19 AM

The differences between NGINX and Apache in terms of community, support and resources are as follows: 1. Although the NGINX community is small, it is active and professional, and official support provides advanced features and professional services through NGINXPlus. 2.Apache has a huge and active community, and official support is mainly provided through rich documentation and community resources.

NGINX Unit: An Introduction to the Application ServerNGINX Unit: An Introduction to the Application ServerMay 10, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports a variety of programming languages ​​and frameworks, such as Python, PHP, Java, Go, etc. 1. It supports dynamic configuration and can adjust application configuration without restarting the server. 2.NGINXUnit supports multi-language applications, simplifying the management of multi-language environments. 3. With configuration files, you can easily deploy and manage applications, such as running Python and PHP applications. 4. It also supports advanced configurations such as routing and load balancing to help manage and scale applications.

Using NGINX: Optimizing Website Performance and ReliabilityUsing NGINX: Optimizing Website Performance and ReliabilityMay 09, 2025 am 12:19 AM

NGINX can improve website performance and reliability by: 1. Process static content as a web server; 2. forward requests as a reverse proxy server; 3. allocate requests as a load balancer; 4. Reduce backend pressure as a cache server. NGINX can significantly improve website performance through configuration optimizations such as enabling Gzip compression and adjusting connection pooling.

NGINX's Purpose: Serving Web Content and MoreNGINX's Purpose: Serving Web Content and MoreMay 08, 2025 am 12:07 AM

NGINXserveswebcontentandactsasareverseproxy,loadbalancer,andmore.1)ItefficientlyservesstaticcontentlikeHTMLandimages.2)Itfunctionsasareverseproxyandloadbalancer,distributingtrafficacrossservers.3)NGINXenhancesperformancethroughcaching.4)Itofferssecur

NGINX Unit: Streamlining Application DeploymentNGINX Unit: Streamlining Application DeploymentMay 07, 2025 am 12:08 AM

NGINXUnit simplifies application deployment with dynamic configuration and multilingual support. 1) Dynamic configuration can be modified without restarting the server. 2) Supports multiple programming languages, such as Python, PHP, and Java. 3) Adopt asynchronous non-blocking I/O model to improve high concurrency processing performance.

NGINX's Impact: Web Servers and BeyondNGINX's Impact: Web Servers and BeyondMay 06, 2025 am 12:05 AM

NGINX initially solved the C10K problem and has now developed into an all-rounder who handles load balancing, reverse proxying and API gateways. 1) It is well-known for event-driven and non-blocking architectures and is suitable for high concurrency. 2) NGINX can be used as an HTTP and reverse proxy server, supporting IMAP/POP3. 3) Its working principle is based on event-driven and asynchronous I/O models, improving performance. 4) Basic usage includes configuring virtual hosts and load balancing, and advanced usage involves complex load balancing and caching strategies. 5) Common errors include configuration syntax errors and permission issues, and debugging skills include using nginx-t command and stub_status module. 6) Performance optimization suggestions include adjusting worker parameters, using gzip compression and

Nginx Troubleshooting: Diagnosing and Resolving Common ErrorsNginx Troubleshooting: Diagnosing and Resolving Common ErrorsMay 05, 2025 am 12:09 AM

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.

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 Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools