基本配置来源:community-scripts:2fa
针对 2FAuth 这种涉及极端敏感数据(OTP 密钥)的应用,Nginx 的配置核心在于:强制加密、防止劫持、以及正确处理 Laravel 的伪静态路由。
以下是为你优化后的 Nginx Server 块配置。
1. 2FAuth 专用 Nginx 配置文件
建议将此内容写入 /etc/nginx/sites-available/2fauth,然后通过 ln -s 链接到 sites-enabled。
server {
listen 80;
listen [::]:80;
server_name 2fa.yourdomain.com; # 替换为你的域名或 IP
# 自动跳转 HTTPS (如果你已配置证书)
# return 301 https://$host$request_uri;
root /opt/2fauth/public; # 必须指向 public 目录
index index.php index.html;
# --- 安全响应头 ---
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "upgrade-insecure-requests";
# 开启 HSTS (需配合 HTTPS 使用)
# add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# 处理 PHP 脚本 (核心部分)
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# 请根据容器内 php-fpm 的实际版本修改(如 8.2 或 8.3)
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 禁止访问敏感文件
location ~ /\.(?!well-known).* {
deny all;
}
# 静态资源缓存优化
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|otf)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
access_log off;
}
error_log /var/log/nginx/2fauth.error.log;
access_log /var/log/nginx/2fauth.access.log;
}
2. 针对性优化要点说明
- 根目录 (
root /opt/2fauth/public):这是新手最容易出错的地方。必须指向public子目录,否则会导致核心代码暴露,且无法正确加载入口文件。 - 伪静态 (
try_files):2FAuth 使用 Laravel 框架。如果没有这一行,除了首页能打开,点击其他任何菜单都会报 Nginx 404。 - 安全头部 (Security Headers):
X-Frame-Options: 防止你的 2FA 库被嵌套在非法网页的iframe中。X-Content-Type-Options: 强制浏览器遵循 MIME 类型,防止黑客通过伪造文件头进行攻击。- 静态资源缓存:2FAuth 是单页应用(SPA),静态资源较多。设置 30 天缓存并关闭日志能显著提升加载速度。
3. 如何应用配置
- 检查 PHP 版本:
在容器内输入ls /var/run/php/,查看具体的.sock文件名(例如是php8.2-fpm.sock还是php8.3-fpm.sock),并对应修改配置中的fastcgi_pass。 测试并重启:
nginx -t # 检查语法是否正确 systemctl reload nginx修复权限(如果网页打不开):
确保 Nginx 用户有权访问目录:chown -R www-data:www-data /opt/2fauth chmod -R 755 /opt/2fauth/storage