网站根目录构建、服务器配置与安全加固实践
根目录的初始化与命名策略
Web服务的根目录(DocumentRoot)是浏览器请求映射到服务器文件系统的基础锚点。在类Unix环境中,虽然传统路径多位于/var/www,但现代部署更推荐根据业务隔离需求自定义路径。初始化操作可通过图形化传输工具或终端指令完成。
创建与赋权流程
通过终端执行是最直接且可审计的方式。以下为标准化创建步骤:
# 建立目标路径
sudo mkdir -p /srv/web/app-core
# 绑定Web服务运行账户
sudo chown -R www:www /srv/web/app-core
# 赋予标准读写执行权限
sudo chmod -R 755 /srv/web/app-core
目录命名规范
科学的命名有助于后期运维。建议遵循以下原则:
- 业务标识法:使用项目缩写或域名主体(如
client_dashboard、shop_v2) - 环境隔离法:附加阶段后缀(如
staging_assets、live_frontend) - 字符限制:仅使用小写英文、数字及中划线,严禁包含空格或特殊符号
Web服务器虚拟主机映射
创建目录后,需将域名请求准确指向该路径。以下是Apache与Nginx的核心配置范式。
Apache 2.4 配置模板
配置文件通常存放于/etc/apache2/sites-available/,示例如下:
<VirtualHost *:80>
ServerName main.site.com
ServerAlias www.main.site.com
ServerAdmin ops@main.site.com
DocumentRoot /srv/web/app-core/public
# 日志分流
ErrorLog ${APACHE_LOG_DIR}/main.site_err.log
CustomLog ${APACHE_LOG_DIR}/main.site_req.log combined
<Directory "/srv/web/app-core/public">
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 动态脚本处理
<FilesMatch "\.ph(p3?|tml)$">
SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost"
</FilesMatch>
</VirtualHost>
激活站点并重载服务:
sudo a2ensite main.site.conf
sudo apachectl graceful
Nginx 配置模板
Nginx配置侧重于高效的路由匹配与静态资源处理:
server {
listen 80;
server_name main.site.com www.main.site.com;
root /srv/web/app-core/public;
index index.php index.html;
access_log /var/log/nginx/main.site.access.log;
error_log /var/log/nginx/main.site.error.log warn;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 阻断敏感后缀访问
location ~* \.(env|git|bak|sql)$ {
return 403;
}
}
软链接至启用目录并验证语法后重载:
sudo ln -sf /etc/nginx/sites-available/main.site /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
请求解析链路与静态结构规划
当客户端发起请求时,Web服务器会经历DNS解析、端口监听匹配、虚拟主机路由,最终在配置的根目录下查找相对路径对应的物理文件。若匹配到静态资源(如.css、.png)则直接输出;若为动态脚本,则交由后端解释器或FastCGI进程处理。
推荐的应用目录树
现代架构通常采用单一入口设计,将公开资源与核心逻辑物理隔离:
/srv/web/app-core
├── public/ # 唯一对外暴露目录
│ ├── index.php # 请求统一入口
│ ├── uploads/ # 用户文件存储
│ └── static/ # JS/CSS/图片资源
├── src/ # 业务逻辑层
│ ├── routes/
│ ├── handlers/
│ └── middleware/
├── config/ # 运行时参数
│ └── services.yaml
├── storage/ # 缓存与日志
│ ├── framework/
│ └── runtime/
└── .env.production # 环境变量(严禁置于public内)
路由映射对照表
| 浏览器地址 | 物理文件路径 | 处理机制 |
|---|---|---|
/ | public/index.php | 前端控制器接管 |
/api/users | public/index.php | 内部路由分发 |
/static/app.js | public/static/app.js | 静态文件直出 |
访问控制与纵深防御
根目录安全不仅依赖防火墙,更需在Web服务器层配置严格的访问策略。
Apache 规则强化
在根目录或public目录下放置.htaccess可实施细粒度控制:
# 关闭目录浏览
Options -Indexes
# 启用重写引擎
RewriteEngine On
# 伪静态处理:非真实文件/目录的请求转发至入口
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php [QSA,L]
# 拦截危险后缀
<FilesMatch "\.(git|htaccess|log|ini)$">
Require all denied
</FilesMatch>
Nginx 对应策略
location / {
try_files $uri $uri/ =404;
}
location ~* \.(git|htaccess|log|ini|bak)$ {
deny all;
access_log off;
log_not_found off;
}
权限模型与安全加固
Linux文件系统权限是防止越权读写的第一道防线。建议采用最小权限原则(Least Privilege)。
精细化的用户组管理
# 建立运维专属组
sudo groupadd deployers
sudo usermod -aG deployers www
sudo usermod -aG deployers $USER
# 调整属主与属组
sudo chown -R $USER:deployers /srv/web/app-core
sudo find /srv/web/app-core -type d -exec chmod 775 {} \;
sudo find /srv/web/app-core -type f -exec chmod 664 {} \;
# 上传目录特殊处理(允许Web写入)
sudo chown -R www:www /srv/web/app-core/public/uploads
sudo chmod -R 775 /srv/web/app-core/public/uploads
响应头与协议限制
通过安全头部防御XSS、点击劫持及MIME嗅探攻击。Apache配置示例:
<Directory "/srv/web/app-core/public">
Options -Indexes -ExecCGI
AllowOverride None
Require all granted
# 仅允许标准请求方法
<LimitExcept GET POST HEAD>
Require all denied
</LimitExcept>
# 安全响应头注入
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "DENY"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header always unset Server
</Directory>
Nginx等效实现:
server {
# ... 基础配置 ...
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "no-referrer" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'" always;
server_tokens off;
}
自动化巡检与日志审计
定期执行脚本可快速识别权限异常或非法注入文件。以下为Bash巡检示例:
#!/usr/bin/env bash
TARGET_DIR="/srv/web/app-core"
echo ">>> 扫描目录权限异常..."
find "$TARGET_DIR" -type d ! -perm 775 -ls
echo ">>> 扫描文件权限异常..."
find "$TARGET_DIR" -type f ! -perm 664 -ls
echo ">>> 检索非预期脚本文件..."
find "$TARGET_DIR" -name "*.php" -o -name "*.sh" | grep -vE "(public|src)" | grep -v "vendor"
echo ">>> 列出近三日修改项..."
find "$TARGET_DIR" -type f -mtime -3 -exec ls -lh {} \;
日志分析应重点关注高频404状态码、路径穿越尝试(如../)、异常大体积POST请求以及非业务时段的访问峰值。结合logrotate实现日志分卷归档,并保留60至90天的历史数据以供溯源。