MrDoc 文件系统部署
Docker 镜像部署MrDoc
使用 Nginx + uWSGI 部署 MrDoc
🔧 解决 cryptography 模块缺失问题
MrDoc防爬虫、复制处理探究--部分实现
本文档使用 MrDoc 发布
-
+
首页
MrDoc防爬虫、复制处理探究--部分实现
接上回,先说说数据迁移的作用 ## 📊 数据迁移的作用 ### 数据迁移是什么? 数据迁移是 Django 框架用来管理数据库结构变更的机制。它相当于数据库的"版本控制"。 ### 迁移的作用: 1. **创建数据库表结构** - 根据模型定义创建表 2. **同步数据库变更** - 当模型修改时,自动生成对应的 SQL 3. **维护数据完整性** - 确保代码与数据库结构一致 4. **版本回滚** - 可以回退到之前的数据库状态 ### 迁移到哪里了? * **迁移文件位置**:`/www/wwwroot/MrDoc/*/migrations/` 目录下 * **数据库位置**:默认使用 SQLite,数据库文件在 `/www/wwwroot/MrDoc/db.sqlite3` * **执行记录**:Django 会在数据库中创建 `django_migrations` 表记录所有已执行的迁移 ## 🌐 生产环境配置(8000 端口映射) ### 方案一:使用 Nginx 反向代理(推荐) #### 1. 安装和配置 uWSGI **bash** 复制 下载 ``` # 安装 uWSGI pip install uwsgi # 创建 uWSGI 配置文件 cat > /www/wwwroot/MrDoc/mrdoc_uwsgi.ini << 'EOF' [uwsgi] chdir = /www/wwwroot/MrDoc module = MrDoc.wsgi:application home = /www/wwwroot/MrDoc/venv master = true processes = 4 socket = 127.0.0.1:8008 vacuum = true daemonize = /www/wwwroot/MrDoc/uwsgi.log static-map = /static=/www/wwwroot/MrDoc/static EOF ``` #### 2. 配置 Nginx **bash** 复制 下载 ``` # 安装 Nginx yum install nginx -y # 创建 Nginx 配置文件 cat > /etc/nginx/conf.d/mrdoc.conf << 'EOF' server { listen 80; server_name 你的域名.com; # 修改为你的域名或IP # 静态文件处理 location /static/ { alias /www/wwwroot/MrDoc/static/; expires 30d; add_header Cache-Control public; } # 媒体文件处理 location /media/ { alias /www/wwwroot/MrDoc/media/; expires 30d; } # 动态请求转发给 uWSGI location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8008; uwsgi_read_timeout 300; # 安全头 add_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff; } # 禁止访问敏感文件 location ~ /\. { deny all; } location ~ /(config|data)/ { deny all; } } EOF ``` #### 3. 启动服务 **bash** 复制 下载 ``` # 启动 uWSGI cd /www/wwwroot/MrDoc uwsgi --ini mrdoc_uwsgi.ini # 测试 Nginx 配置 nginx -t # 启动 Nginx systemctl start nginx systemctl enable nginx ``` ### 方案二:直接使用域名访问(简单) 如果你有域名,可以直接配置域名解析到服务器 IP,然后通过域名:8000 访问,但这不够专业。 ## 🛡️ 防复制、防爬虫详细方案 ### 1. 前端防复制措施 #### 在模板中添加防复制代码 **bash** 复制 下载 ``` # 编辑基础模板 vi /www/wwwroot/MrDoc/templates/base.html ``` 在 `</head>` 标签前添加: **html** 复制 下载 运行 ``` <style> /* 禁止文本选择 */ body { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; } /* 允许代码块选择(方便查看代码) */ pre, code { -webkit-user-select: text; -moz-user-select: text; -ms-user-select: text; user-select: text; } </style> <script> // 禁用右键菜单 document.addEventListener('contextmenu', function(e) { e.preventDefault(); return false; }); // 禁用选择开始事件 document.addEventListener('selectstart', function(e) { e.preventDefault(); return false; }); // 禁用键盘快捷键 document.addEventListener('keydown', function(e) { // 禁用 Ctrl+C, Ctrl+A, Ctrl+U, F12 if (e.ctrlKey && (e.keyCode === 67 || e.keyCode === 65 || e.keyCode === 85) || e.keyCode === 123) { // F12 e.preventDefault(); return false; } }); // 防止拖拽 document.addEventListener('dragstart', function(e) { e.preventDefault(); return false; }); </script> ``` ### 2. Nginx 层面防爬虫 #### 在 Nginx 配置中添加: **nginx** 复制 下载 ``` server { # ... 其他配置 ... # 限制爬虫访问频率 limit_req_zone $binary_remote_addr zone=api:10m rate=1r/s; limit_req_zone $binary_remote_addr zone=general:10m rate=10r/m; # 阻止常见爬虫 User-Agent if ($http_user_agent ~* (bot|crawl|spider|scraper|python|curl|wget|httrack)) { return 444; } # 阻止空 User-Agent if ($http_user_agent = "") { return 444; } # API 接口限流 location /api/ { limit_req zone=api burst=5 nodelay; # ... 其他配置 ... } # 通用限流 location / { limit_req zone=general burst=20 nodelay; # ... 其他配置 ... } # 添加安全头 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=31536000; includeSubDomains"; } ``` ### 3. Django 层面防护 #### 创建中间件 **bash** 复制 下载 ``` # 创建防爬虫中间件 cat > /www/wwwroot/MrDoc/middleware/anti_spider.py << 'EOF' import time from django.http import HttpResponseForbidden from django.core.cache import cache class AntiSpiderMiddleware: def __init__(self, get_response): self.get_response = get_response self.spider_user_agents = [ 'bot', 'crawl', 'spider', 'scraper', 'python', 'curl', 'wget', 'httrack', 'screaming', 'scan' ] def __call__(self, request): user_agent = request.META.get('HTTP_USER_AGENT', '').lower() # 检测爬虫 User-Agent if any(bot in user_agent for bot in self.spider_user_agents): return HttpResponseForbidden('Access Denied') # 空 User-Agent if not user_agent.strip(): return HttpResponseForbidden('Access Denied') # 频率限制(基于IP) ip = self.get_client_ip(request) cache_key = f"request_count_{ip}" request_count = cache.get(cache_key, 0) if request_count > 100: # 每分钟最多100个请求 return HttpResponseForbidden('Rate limit exceeded') cache.set(cache_key, request_count + 1, 60) # 1分钟过期 return self.get_response(request) def get_client_ip(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip EOF ``` #### 启用中间件 修改 `MrDoc/settings.py`: **python** 复制 下载 ``` MIDDLEWARE = [ # ... 其他中间件 ... 'middleware.anti_spider.AntiSpiderMiddleware', ] ``` ### 4. 添加水印保护 #### 创建水印中间件 **bash** 复制 下载 ``` cat > /www/wwwroot/MrDoc/middleware/watermark.py << 'EOF' from django.utils.deprecation import MiddlewareMixin import re class WatermarkMiddleware(MiddlewareMixin): def process_response(self, request, response): if (response.status_code == 200 and 'text/html' in response.get('Content-Type', '') and not request.path.startswith('/admin/')): content = response.content.decode('utf-8') # 添加水印样式 watermark_css = ''' <style> .watermark { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 9999; background: repeating-linear-gradient( 45deg, transparent, transparent 10px, rgba(0,0,0,0.03) 10px, rgba(0,0,0,0.03) 20px ); } </style> ''' # 插入到head标签后 content = content.replace('</head>', watermark_css + '</head>') # 添加水印div到body开始 watermark_div = '<div class="watermark"></div>' content = content.replace('<body>', '<body>' + watermark_div) response.content = content.encode('utf-8') return response EOF ``` ### 5. robots.txt 控制 **bash** 复制 下载 ``` # 创建 robots.txt cat > /www/wwwroot/MrDoc/static/robots.txt << 'EOF' User-agent: * Disallow: /admin/ Disallow: /api/ Disallow: /search/ Disallow: /upload/ User-agent: GPTBot Disallow: / User-agent: ChatGPT-User Disallow: / User-agent: Google-Extended Disallow: / EOF ``` ## 🚀 完整部署脚本 **bash** 复制 下载 ``` cat > deploy_production.sh << 'EOF' #!/bin/bash cd /www/wwwroot/MrDoc source venv/bin/activate echo "1. 停止开发服务器..." pkill -f "python manage.py runserver" echo "2. 安装 uWSGI..." pip install uwsgi echo "3. 创建必要目录..." mkdir -p /www/wwwroot/MrDoc/media mkdir -p /www/wwwroot/MrDoc/static echo "4. 收集静态文件..." python manage.py collectstatic --noinput echo "5. 启动 uWSGI..." uwsgi --ini mrdoc_uwsgi.ini echo "6. 配置 Nginx..." # 使用上面的 Nginx 配置 echo "部署完成!" echo "访问地址: http://你的域名" EOF chmod +x deploy_production.sh ``` ## 💡 重要提醒 1. **防复制局限性**:前端防复制措施只能阻止普通用户,无法阻止技术用户 2. **性能影响**:过多的防护措施可能影响网站性能 3. **用户体验**:平衡安全性和用户体验 4. **定期备份**:定期备份数据库和媒体文件
沧岚
2025年10月30日 09:34
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
PDF文档(打印)
分享
链接
类型
密码
更新密码