【Azure 應用服務】PHP應用部署在App Service for Linux環境中,上傳檔案大於1MB時,遇見了413 Request Entity Too Large 錯誤的解決方法

2022-07-27 06:04:04

問題描述

在PHP專案部署在App Service後,上傳檔案如果大於1MB就會遇見 413 Request Entity Too Large 的問題。

 

問題解決

目前這個問題,首先需要分析應用所在的環境。 在App Service for Linux環境中,為PHP提供的執行時當前只有PHP 8.0, 並且 PHP 8.0 中使用的Nginx作為代理伺服器。然後請求才會傳遞到PHP應用中。

基於以上分析,在PHP應用中,會收到Nginx 和PHP雙重限制。所以傳遞檔案的限制問題設計到兩個方面:

一:Nginx 伺服器對上傳檔案大小的限制。(預設限制為 1 MB,需通過 client_max_body_size 引數修改大小)

二:PHP 對上傳檔案檔案大小的限制。(預設限制為 2MB,可以通過 upload_max_filesize 和 post_max_size 修改大小)

所以,本文主要介紹,如何在App Service For Linux環境中,修改Nginx對檔案大小的限制和PHP檔案大小的限制。

 

第一部分:修改 Nginx client_max_body_size

第一步:進入App Service SSH 頁面,尋找Nginx的default檔案,路徑為( /etc/nginx/sites-available/default),通過CAT檢視預設的內容。

上圖中執行的指令有:

cd ..

cd etc/nginx/sites-availabled

ls

cat default

 

第二步:複製default的內容到本地自己的PHP專案檔案中,新增client_max_body_size後,隨專案檔案一起部署到 /home/site/wwwroot/目錄下

(PS: 目錄可以自定義修改,但必須注意,如果專案部署的根目錄不在wwwroot中,必須同步修改 nginx 的 default組態檔,避免應用報錯找不到原始檔)

default的預設內容為

server {
    #proxy_cache cache;
        #proxy_cache_valid 200 1s;
    listen 8080;
    listen [::]:8080;
    root /home/site/wwwroot;
    index  index.php index.html index.htm;
    server_name  example.com www.example.com; 

    location / {            
        index  index.php index.html index.htm hostingstart.html;
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /html/;
    }
    
    # Disable .git directory
    location ~ /\.git {
        deny all;
        access_log off;
        log_not_found off;
    }

    # Add locations of phpmyadmin here.
    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_connect_timeout         300; 
        fastcgi_send_timeout           3600; 
        fastcgi_read_timeout           3600;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }
}

需要在其中新增  client_max_body_size , 比如這裡設定為10m  (不要寫成 10MB,並且結尾要帶上分號)

server {
    #proxy_cache cache;
    #proxy_cache_valid 200 1s;
    listen 8080;
    listen [::]:8080;
    root /home/site/wwwroot;
    index  index.php index.html index.htm;
    server_name  lbphplinuxtest01.chinacloudsites.cn;
    client_max_body_size 10m;

   location / {
        try_files $uri $uri/ /index.php$is_args$query_string;
        index  index.php index.html index.htm hostingstart.html;
    }

   # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /html/;
    }
    
    # Disable .git directory
    location ~ /\.git {
        deny all;
        access_log off;
        log_not_found off;
    }

   # Add locations of phpmyadmin here.
    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_connect_timeout         300;
        fastcgi_send_timeout           3600;
        fastcgi_read_timeout           3600;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }
}

 

第三步:PHP應用檔案部署後,可以也SSH中通過cp 命令把修改後的default檔案複製到 nginx sites-available default目錄下,並且重啟Nginx服務(service nginx restart)。此步為臨時性有效。

此步執行的命令為

##複製 default 到nginx sites-available目錄中
cp /home/site/wwwroot/default /etc/nginx/sites-available/default

##重新載入 nginx 服務
service nginx reload 

如果通過SSH直接在應用的容器中執行以上命令,當App Service站點重啟,應用重新部署時,以上修改都會丟失,Nginx設定會恢復預設。所以需要下一步永久性操作。

PS: 修改完成後,可以通過 Nginx -T 來檢視Nginx所使用的設定引數。以及可以在 /var/log/nginx中檢視error.log紀錄檔

root@49eebca54055:~# nginx -T
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# configuration file /etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 10068;
        multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log off;
        error_log /dev/stderr;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
# 
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

# configuration file /etc/nginx/modules-enabled/50-mod-http-auth-pam.conf:
load_module modules/ngx_http_auth_pam_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-dav-ext.conf:
load_module modules/ngx_http_dav_ext_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-echo.conf:
load_module modules/ngx_http_echo_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-geoip.conf:
load_module modules/ngx_http_geoip_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-image-filter.conf:
load_module modules/ngx_http_image_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-subs-filter.conf:
load_module modules/ngx_http_subs_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-upstream-fair.conf:
load_module modules/ngx_http_upstream_fair_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-xslt-filter.conf:
load_module modules/ngx_http_xslt_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-mail.conf:
load_module modules/ngx_mail_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-stream.conf:
load_module modules/ngx_stream_module.so;

# configuration file /etc/nginx/mime.types:

types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/javascript                js;
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

    application/font-woff                 woff;
    application/java-archive              jar war ear;
    application/json                      json;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai;
    application/rtf                       rtf;
    application/vnd.apple.mpegurl         m3u8;
    application/vnd.ms-excel              xls;
    application/vnd.ms-fontobject         eot;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z;
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/xspf+xml                  xspf;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
    application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp2t                            ts;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}

# configuration file /etc/nginx/sites-enabled/default:
server {
    #proxy_cache cache;
    #proxy_cache_valid 200 1s;
    listen 8080;
    listen [::]:8080;
    root /home/site/wwwroot;
    index  index.php index.html index.htm;
    server_name  lbphplinuxtest01.chinacloudsites.cn;
    client_max_body_size 10m;


   location / {
        try_files $uri $uri/ /index.php$is_args$query_string;
        index  index.php index.html index.htm hostingstart.html;
    }



   # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /html/;
    }
    
    # Disable .git directory
    location ~ /\.git {
        deny all;
        access_log off;
        log_not_found off;
    }



   # Add locations of phpmyadmin here.
    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_connect_timeout         300;
        fastcgi_send_timeout           3600;
        fastcgi_read_timeout           3600;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }
}
# configuration file /etc/nginx/fastcgi_params:

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

root@49eebca54055:~# 
View Code

 

第四步:把第三步的 cp 命令和 restart命令設定在 App Service的啟動命令中,以便長久有效。如果啟動命令中內容過多,可以把全部內容寫入到一個指令碼檔案中(如 startscript.sh),並隨專案檔案一起放置。然後把檔案全路徑填入啟動命令中。

把第三步的兩句命令用分號(;)連線在一起設定在Startup Command中,操作如下圖:

cp /home/site/wwwroot/default /etc/nginx/sites-available/default; service nginx reload

1)在App Service的目錄頁面中, 點選Configuration目錄進入Configuration頁面

2)選擇General Settings索引標籤

3)在Startup Command中新增 cp和restart命令

4)點選儲存按鈕。應用會自動重啟並執行命令

注意:當以上操作完成後,Nginx上傳檔案預設1MB 的限制就變為了 10MB,但是因為PHP的限制還沒有修改,所以當在應用中上傳檔案大於2MB時候,依舊會收到 413 或者 404 錯誤。只是,此時錯誤的根源為PHP限制。

 

第二部分:修改PHP upload_max_filesize 和 post_max_size 

第一步:在專案檔案根目錄中建立 extensions.ini 的檔案,並在其中設定 upload_max_filesize 和 post_max_size 值為50M。然後把修改後的檔案一起部署到 wwwroot中

或者也可以直接在 SSH中通過命令建立 extensions.ini 檔案和內容

cd site
mkdir ini
cd ini
echo "upload_max_filesize=50M"  >> extensions.ini 
echo "post_max_size=50M"  >> extensions.ini 
cat extensions.ini
ls

 

第二步:回到Azure App Service 門戶頁面,在Application Setting中新增 PHP_INI_SCAN_DIR 引數,指定它的值為 /usr/local/etc/php/conf.d:/home/site/ini  或者 /usr/local/etc/php/conf.d:/home/site/wwwroot/ini

PS:  前一段 /usr/local/etc/php/conf.d 路徑固定,為PHP Runtime載入設定組態檔的路徑,而一部分 /home/site/ini 則需要根據第一步extensions.ini檔案的路徑而改變

 

第三步: 通過phpinfo()函數驗證修改後的引數

在info.php檔案中寫入  <?php phpinfo();      ,然後通過url存取 https://<sitename>.chinacloudsites.cn/info.php 

 echo "<?php phpinfo();" >> info.php

 

 

 

附錄:PHP上傳檔案的可用程式碼

W3School PHP File Upload : https://www.w3schools.com/php/php_file_upload.asp

 

 

參考資料

NGINX Rewrite Rules for Azure App Service Linux PHP 8.x:https://azureossd.github.io/2021/09/02/php-8-rewrite-rule/index.html  

Azure App Service Linux - Update PHP Settings:https://azureossd.github.io/2019/01/29/azure-app-service-linux-update-php-settings/

 

 

 

[END]