Advertisement
Nickpips

setup_nginx.sh

Mar 1st, 2025
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.17 KB | None | 0 0
  1. #!/bin/bash
  2. set -euo pipefail
  3. error_handler() {
  4.     echo "Error on line ${BASH_LINENO[0]}: ${BASH_COMMAND}"
  5. }
  6. trap 'error_handler' ERR
  7.  
  8. # Get the domain name
  9. if [[ -n "$1" ]]; then
  10.     FULL_DOMAIN_NAME="$1"
  11. else
  12.     read -p "Enter the full domain name (e.g., api.example.com): " FULL_DOMAIN_NAME
  13. fi
  14. DOMAIN_NAME="${FULL_DOMAIN_NAME#*.}"
  15.  
  16. # Install https certificates
  17. sudo apt-get update
  18. sudo apt-get install -y nginx certbot python3-certbot-nginx
  19. sudo certbot --nginx -d $FULL_DOMAIN_NAME --non-interactive --agree-tos -m admin@$DOMAIN_NAME
  20.  
  21. # Setup nginx.conf
  22. IP_ADDRESS=localhost
  23. sudo tee /etc/nginx/nginx.conf >/dev/null <<EOF
  24. user www-data;
  25. worker_processes auto;
  26. pid /run/nginx.pid;
  27. error_log /var/log/nginx/error.log;
  28. include /etc/nginx/modules-enabled/*.conf;
  29.  
  30. events {
  31.     worker_connections 1000;
  32. }
  33.  
  34. http {
  35.     client_max_body_size 100M;
  36.  
  37.     upstream backend {
  38.         server $IP_ADDRESS:8000;
  39.     }
  40.  
  41.     # Server block
  42.     server {
  43.         server_name $FULL_DOMAIN_NAME;
  44.  
  45.         location / {
  46.             proxy_pass http://backend;
  47.             proxy_set_header Host \$host;
  48.             proxy_set_header X-Real-IP \$remote_addr;
  49.             proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
  50.             proxy_set_header X-Forwarded-Proto https;
  51.         }
  52.  
  53.         # SSL settings (Certbot)
  54.         listen [::]:443 ssl ipv6only=on default_server; # managed by Certbot
  55.         listen 443 ssl default_server; # managed by Certbot
  56.         ssl_certificate /etc/letsencrypt/live/$FULL_DOMAIN_NAME/fullchain.pem; # managed by Certbot
  57.         ssl_certificate_key /etc/letsencrypt/live/$FULL_DOMAIN_NAME/privkey.pem; # managed by Certbot
  58.         include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  59.         ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
  60.     }
  61.  
  62.     # HTTP -> HTTPS redirect
  63.     server {
  64.         if (\$host = $FULL_DOMAIN_NAME) {
  65.             return 301 https://\$host\$request_uri;
  66.         }
  67.         listen 80 default_server;
  68.         listen [::]:80 default_server;
  69.         server_name $FULL_DOMAIN_NAME;
  70.         return 404;
  71.     }
  72. }
  73. EOF
  74.  
  75. # Reload nginx
  76. sudo nginx -t
  77. sudo nginx -s reload
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement