code

Configuring HTTPS for Nginx

Last updated: 21.02.2026
Views: 207

HTTPS stands for Hypertext Transfer Protocol Secure, and it is the secure version of HTTP, the protocol used for communication between your web browser and a website. HTTPS encrypts the data being sent and received, ensuring that the communication is secure and private.

Some time ago I used VPS for some of my projects. I needed to run PHP and NodeJS on the server and set up domains for these projects. Nginx was chosen as a proxy server, on which the domains were set up. The operating system on the server was Ubuntu. For the domains to work, HTTPS had to be set up. To generate SSL certificates, the free Let’s Encrypt certification center was chosen.

Get a certificate

sudo letsencrypt certonly -a webroot --webroot-path=/var/www/site.com/public_html -d site.com -d www.site.com

Renew the certificate

sudo letsencrypt renew

Full nginx config

server {
 
    listen 80 ;
    server_name  site.com.ru www.site.com;
    return 301 https://$server_name$request_uri;
 }
 
server {
 
  # SSL configuration
 
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  server_name  site.com www.site.com;
 
  ssl_certificate /etc/letsencrypt/live/site.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/site.com/privkey.pem;
  ssl_trusted_certificate /etc/letsencrypt/live/site.com/chain.pem;
 
  add_header Content-Security-Policy "img-src https: data:; upgrade-insecure-requests";
 
  # We keep access log:
  access_log  /var/log/nginx/site.com_access.log;
 
  # We share static and dynamic, static stored in cache for 10 days:
      location ~* \.(jpg|jpeg|gif|png|ico|css|bmp|swf|js|doc|docx|pdf|xls|xlsx|rar|zip|tbz|7z|exe)$ {
      root /var/www/site.com/public_html;
      expires 10d;
  }
  # htaccess and htpasswd do not give:
      location ~ /\.ht {
          deny  all;
  }
 
  # We want to see statistics when accessing the /stat folder
  location = /stat {
      stub_status on;
      access_log  off;
  }
 
  location / {
      proxy_pass         http://site.com:8888/;
      proxy_redirect     off;
      log_not_found      off;
      proxy_set_header   X-Real-IP $remote_addr;
      proxy_set_header   Host $http_host;
      proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header   HTTPS on;
  }
}

Do not forget to restart nginx

sudo /etc/init.d/nginx restart
author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

Leave a Reply

Your email address will not be published. Required fields are marked *