Шаблон nginx конфига
FastAPI + Uvicorn + SSL
FastAPI через Uvicorn с полноценным HTTPS. Автоматический редирект HTTP→HTTPS, современные протоколы TLSv1.2/TLSv1.3, HSTS, оптимизированный SSL-кэш сессий. Подходит для production-деплоя с Let's Encrypt.
Пример конфига
nginx.conf
upstream fastapi_backend {
server 127.0.0.1:8000;
keepalive 32;
}
# HTTP → HTTPS редирект
server {
listen 80;
listen [::]:80;
server_name example.com;
return 301 https://$host$request_uri;
}
# HTTPS сервер
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
server_tokens off;
client_max_body_size 20m;
access_log /var/log/nginx/fastapi-access.log combined;
error_log /var/log/nginx/fastapi-error.log warn;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
gzip on;
gzip_vary on;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript text/xml image/svg+xml;
location /static/ {
alias /var/www/app/static/;
expires 30d;
add_header Cache-Control "public, immutable";
}
location / {
proxy_pass http://fastapi_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_read_timeout 120s;
proxy_connect_timeout 30s;
proxy_buffering on;
proxy_buffer_size 8k;
proxy_buffers 8 32k;
}
location ~ /\. {
deny all;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
Как настроить
-
Получите SSL-сертификат: certbot --nginx -d example.com
-
Убедитесь что certbot создал файлы fullchain.pem и privkey.pem в /etc/letsencrypt/live/example.com/
-
Запустите Uvicorn/Gunicorn на 127.0.0.1:8000
-
Скопируйте конфиг в /etc/nginx/sites-available/example.com и активируйте
-
Проверьте синтаксис: nginx -t && systemctl reload nginx
-
Проверьте SSL на ssllabs.com/ssltest — должен быть рейтинг A или A+