正确配置Nginx支持ThinkPHP 6需设置URL重写将请求导向public/index.php,隐藏index.php并启用pathinfo;通过location规则禁止访问app、config、.env、.git等敏感目录和文件;为静态资源设置长效缓存与Gzip压缩提升性能;同时关闭PHP错误显示、限制open_basedir、禁用上传目录执行权限,并配置HTTPS增强安全性。
在Nginx服务器上部署ThinkPHP框架时,合理的配置不仅能提升访问速度,还能增强安全性与稳定性。以下是针对ThinkPHP(以ThinkPHP 6为例)在Nginx环境下的最佳实践配置方案。
正确设置入口文件和重写规则
ThinkPHP使用public/index.php作为唯一入口,所有请求都应被引导至此文件,同时隐藏index.php有助于SEO和URL美观。
Nginx需配置URL重写规则,将非静态资源请求转发给index.php处理:
location / { # 指定首页 index index.html index.htm index.php; <pre class='brush:php;toolbar:false;'># 尝试匹配静态文件,否则交给index.php if (!-e $request_filename) { rewrite ^/(.*)$ /index.php/$1 last; break; }
}
立即学习“PHP免费学习笔记(深入)”;
隐藏index.php的另一种方式(兼容pathinfo)
location ~ .php($|/) { fastcgi_pass 127.0.0.1:9000; # 或 unix:/run/php/php-fpm.sock fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }
该配置确保动态请求交由PHP-FPM处理,并支持ThinkPHP的路由解析。
禁止访问敏感目录和文件
ThinkPHP的app、config、vendor等目录不应通过Web直接访问,防止源码泄露。
在server块中添加以下限制:
location ~ ^/(app|config|database|extend|runtime|vendor)/ { deny all; } <h1>禁止访问 .env、.git 等敏感文件</h1><p>location ~ /.env|.git|.ht { deny all; }</p>
这些规则有效防止关键配置文件被下载。
优化静态资源处理
合理缓存静态资源可显著降低服务器负载并加快页面加载速度。
为静态文件设置过期时间并启用Gzip压缩:
location ~* .(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off; log_not_found off; } <h1>启用Gzip压缩</h1><p>gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json image/svg+xml;</p>
这能减少传输体积,提升前端性能。
安全加固建议
生产环境中应关闭错误显示,防止敏感信息泄露。
- 确保display_errors = Off在php.ini中已设置
- 设置正确的open_basedir限制PHP访问范围
- 使用HTTPS并在Nginx中配置SSL证书(推荐Let’s Encrypt)
- 限制上传目录执行权限(如upload目录禁止运行PHP)
location ~* ^/uploads/.*.(php|php5)$ { deny all; }
基本上就这些。一套清晰、安全、高效的Nginx配置能让ThinkPHP应用更稳定地运行在生产环境。关键是入口重写、目录保护、静态资源优化和基础安全措施到位即可满足大多数场景需求。
以上就是nginx thinkphp css php javascript java html js 前端 git json php nginx thinkphp include public location git https ssl unix SEO