|
Shang Gao
www.shanggao.net
© 2000-2026 Shang Gao. All rights reserved. 未经书面许可,不得用于商业用途。
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Read 19
Server Security GuidePractical Server Hardening v1.0.0 1. Overview概述 This guide documents the security practices applied to a PHP website on shared hosting. It's not exhaustive — but it covers the most common attack surfaces: exposed files, browsable directories, and improper access control. 本指南记录在共享主机上运行 PHP 网站时的安全实践。不追求面面俱到,只覆盖最常见的攻击面: 暴露的文件、可浏览的目录、访问控制不当。 Threat Model · 威胁模型
2. File Protection文件保护 Sensitive PHP files (configuration, metadata, shared functions) should not be directly accessible via HTTP. We use a load constant pattern: the file only executes if the caller has defined a specific constant. Pattern · 模式Protected file: <?php
if (!defined('ALLOW_CONFIG_LOAD')) {
http_response_code(404);
exit;
}
return [ ... ];
Caller: define('ALLOW_CONFIG_LOAD', true);
$config = require __DIR__ . '/config.php';
Protected Files · 受保护文件
Why 404, not 403?
3. Directory Protection目录保护 Disable Directory Listing · 禁止目录列表
By default, Apache may serve a directory listing when no Options -Indexes
Sensitive Directories · 敏感目录
For directories that should never be browsed — like Order deny,allow
Deny from all
This returns Directory-Specific Protection
Defense in depth
Using both 4. .htaccess Configuration.htaccess 配置 Root .htaccessPlace in the website root directory: # ============================================
# Security
# ============================================
# Disable directory listing (site-wide)
Options -Indexes
# Protect sensitive files
<FilesMatch "^(config\.php|config-sample\.php)$">
Order deny,allow
Deny from all
</FilesMatch>
Notes on FilesMatch · 关于 FilesMatch
Testing .htaccess · 测试
Nginx note
Nginx does not support 5. Content Visibility内容可见性 Visibility Levels · 可见性级别
Critical Rule · 关键规则
Front-end hiding ≠ back-end protection. Even if a private article is hidden from the listing, the detail page must independently check and return 404. Server-side Check · 服务端检查if (($meta['status'] ?? 'published') !== 'published') {
http_response_code(404);
exit;
}
if (($meta['visibility'] ?? 'public') === 'private') {
http_response_code(404);
exit;
}
6. Error Responses错误响应
7. Checklist检查清单 File Protection
Directory Protection
Content Security
Test URLs · 测试 URL
8. Future Improvements未来改进方向
9. References参考 — End of Guide · 指南结束 — |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||