Ubuntu环境下确保ThinkPHP代码安全的实用清单
一 基础部署与运行环境安全
二 框架与代码层安全
三 文件与目录安全
四 服务器与网络防护
五 Ubuntu Nginx与PHP关键配置示例
server {
listen 443 ssl http2;
server_name your-domain.com;
ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
root /var/www/your-app/public; # 仅指向 public
index index.php index.html;
# 禁止目录索引
autoindex off;
# 禁止敏感目录访问
location ~ ^/(application|thinkphp|vendor|runtime)/ {
deny all;
}
# 禁止上传目录执行 PHP
location /uploads/ {
location ~ \.php$ {
deny all;
}
}
# 统一入口与重写
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP-FPM 处理
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php8.1-fpm.sock; # 版本按实际调整
fastcgi_read_timeout 120;
}
# 安全响应头
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
}
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
memory_limit = 256M
max_execution_time = 30
expose_php = Off
cgi.fix_pathinfo=0
session.cookie_httponly = 1
session.cookie_secure = 1
APP_DEBUG=false
APP_KEY=生成强随机字符串
# 数据库使用环境变量
DB_HOST=127.0.0.1
DB_NAME=your_db
DB_USER=your_user
DB_PASS=your_password
# 项目根与 public
chmod 755 /var/www/your-app
find /var/www/your-app/public -type f -exec chmod 644 {} \;
find /var/www/your-app/public -type d -exec chmod 755 {} \;
# 仅赋予运行用户必要的写权限
chown -R www-data:www-data /var/www/your-app/runtime
chown -R www-data:www-data /var/www/your-app/public/uploads
chmod 750 /var/www/your-app/runtime /var/www/your-app/public/uploads
Options -Indexes