萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Nginx + PHP 配置 open_basedir 限制目錄存取的三種方法

open_basedir 是 PHP 重要的安全機制,限制腳本僅能存取指定目錄樹。在 Nginx + PHP-FPM 架構下,有三種設定方式:

方法一:在 Nginx 站台配置中透過 fastcgi_param 設定

fastcgi_param PHP_VALUE "open_basedir=$document_root:/tmp/:/proc/";

通常站台配置已 include fastcgi.conf;,直接將上述行加入 fastcgi.conf 即可。若單一站台需額外目錄,置於 include fastcgi.conf; 之後可覆蓋預設值。需重啟 Nginx 生效。

方法二:在 php.ini 中以 HOST/PATH 區段設定

[HOST=.]
open_basedir=/home/www/www.45it.com:/tmp/:/proc/

[PATH=/home/www/www.45it.com]
open_basedir=/home/www/www.45it.com:/tmp/:/proc/

需重啟 php-fpm 生效。

方法三:在網站根目錄建立 .user.ini(推薦,無需重啟服務)

open_basedir=/home/www/www.45it.com:/tmp/:/proc/

建議移除 .user.ini 的寫入權限以防竄改。詳細說明請見 PHP 官方文件。

補充:同步禁用危險函數

僅設定 open_basedir 不足以防禦命令執行(如 shell_exec('cat /etc/passwd') 仍可繞過)。建議在 php.ini 同步設定 disable_functions:

disable_functions = pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,eval,popen,passthru,exec,system,shell_exec,proc_open,proc_get_status,chroot,chgrp,chown,ini_alter,ini_restore,dl,pfsockopen,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server,fsocket,chdir
copyright © 萬盛學電腦網 all rights reserved