首页 > 解决方案 > 如何为特定位置块设置 client_max_body_size?

问题描述

Ubuntu 20.04.2 LTS
nginx 1.18.0
php 7.4.15

我有一个多租户 Laravel 应用程序的以下配置

server {
    server_name console.example.com;

    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    ssl_certificate /certs/example.com.crt;
    ssl_certificate_key /certs/example.com.key;
    ssl_session_timeout 1d;
    ssl_session_cache shared:MozSSL:10m;  # about 40000 sessions
    ssl_session_tickets off;

    # modern configuration
    ssl_protocols TLSv1.3;
    ssl_prefer_server_ciphers off;

    # HSTS (ngx_http_headers_module is required) (63072000 seconds)
    add_header Strict-Transport-Security "max-age=63072000" always;

    # OCSP stapling
    ssl_stapling on;
    ssl_stapling_verify on;

    # verify chain of trust of OCSP response using Root CA and Intermediate certs
    ssl_trusted_certificate /certs/example.com.bundle;


    root /home/example/example-console/current/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

#    client_max_body_size 200m;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ [\S-/]+/upload$ {
        client_max_body_size 200m;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

在当前状态下,我收到413 Request Entity Too Large错误。

我使用https://nginx.viraptor.info/来测试匹配和两者https://console.example.com/foo/uploadhttps://console.example.com/foo/bar/upload显示为匹配

当我client_max_body_size 200m;server块中取消注释时,它按预期工作,所以我知道 PHP 没有妨碍。

标签: phplaravelnginx

解决方案


如果您使用try_filesor rewrite,则将client_max_body_size使用更高上下文的 ,而不是您期望的位置块的那个。将您的 PHP 配置移动到您可以包含的文件中并尝试执行以下操作:

location ~ [\S-/]+/upload$ {
    client_max_body_size 200m;
    include /etc/nginx/php-conf.conf;
    rewrite ^(.*)$ /index.php?$query_string break;
}

推荐阅读