Force redirect Http to Https to secure NGINX Web Server

Robioki Denis
2 min readSep 8, 2021

--

Photo by Debby Hudson on Unsplash

Hello, in this tutorial we going to implementation best way to redirect Http port 80 to Https port 443

Make sure you have done setup ssl in your domain and was activate in your nginx

nano /etc/nginx/sites-available/example.com

if ($host = www.example.id) {
return 301 https://$host$request_uri;
} # redirect http to https by rod
if ($host = example.id) {
return 301 https://$host$request_uri;
} # redirect http to https by rod

full config

server {##add this line to redirect http to https 
if ($host = www.example.id) {
return 301 https://$host$request_uri;
} # redirect http to https by rod
if ($host = example.id) {
return 301 https://$host$request_uri;
} # redirect http to https by rod
listen 80;
server_name example.id www.example.id api.example.id;
return 301 https://$server_name$request_uri;
root /var/www/html/example;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
index index.html index.htm index.php;charset utf-8;location / {
try_files $uri $uri/ /index.php?$query_string;
}
access_log /var/log/nginx/nginx.vhost.access.log;
error_log /var/log/nginx/nginx.vhost.error.log;
error_page 404 /index.php;location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}##
server{
listen 443 ssl { .....
}

check nginx configuration using;

sudo nginx -t

reload or restart nginx service using;

sudo service nginx reloadorsudo systemctl restart nginx 

that’s it..

--

--

Robioki Denis
Robioki Denis

Written by Robioki Denis

DevOps Engineer & Fullstack Developer, someone who has a high curiosity 😁

No responses yet