Let’s say Nginx is installed, the site opens via http, and we want it to open via https.
An SSL certificate can be obtained for free from Let’s Encrypt, for example, as I described in the article – Installing Certbot in Ubuntu
We will change the old http configuration to redirect http requests to https, for example:
server {
listen 80;
#listen [::]:80;
server_name example.com;
return 301 https://$server_name:443$request_uri;
}
Now I will give an example configuration for https, the http and https configuration for one site can be placed in one file, for example:
server {
listen 80;
#listen [::]:80;
server_name example.com;
return 301 https://$server_name:443$request_uri;
}
server {
listen 443 ssl;
ssl_protocols TLSv1.2 TLSv1.3;
root /var/www/example;
index index.php;
access_log /var/log/nginx/example_com_access.log;
error_log /var/log/nginx/example_com_error.log;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
ssl_stapling on;
ssl_stapling_verify on;
resolver 127.0.0.1 1.1.1.1 8.8.4.4;
add_header Strict-Transport-Security "max-age=31536000";
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
#fastcgi_pass localhost:9999;
}
location ~ /\. {
deny all;
}
location ~ /\.ht {
deny all;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
}
A similar configuration file can be created for the www.example.com subdomain.
Be sure to check the version of php-fpm installed on your server and change the link, I also specified TLS 1.2, since outdated versions of TLS 1.0 and 1.1 can be used by default.
At the end of the configuration, I denied access to hidden files, turned off logs for robots.txt, favicon.ico files, depending on the site engine and needs, the configuration can be expanded, I left the configuration example for the link below.
See also my articles:
- How to disable TLS 1.0 and TLS 1.1 in Nginx
- Redirect HTTP to HTTPS in Nginx
- Nginx. Parameter default_server
- Install and configure Nginx
- Installing WordPress and Nginx