nginx, http,

Redirect HTTP to HTTPS in Nginx

Dec 26, 2021 · 1 min read · Post a comment

Nowadays almost every owner of a website wants to secure his site with an SSL/TLS certificate. Once that is achieved the second step is to redirect the whole HTTP traffic to HTTPS depending on your web server, which will fully secure the connection between the client and the server. Today I’m going to show you how to redirect HTTP to HTTPS in Nginx.

Prerequisites

  • Nginx
  • Generated SSL/TLS Certificate

Redirect Specific Site

If you hold multiple domains, and you want an HTTPS redirect only for a specific site(domain) then the Nginx HTTP block should look like below:

server {
    listen 80;

    server_name devcoops.com;
    return 301 https://devcoops.com$request_uri;
}

Redirect All HTTP to HTTPS traffic

This block is useful if you need to redirect all sites from HTTP to HTTPS and the best place to put in is the default Nginx configuration file.

server {
    listen 80 default_server;

    server_name _;
    return 301 https://$host$request_uri;
}
  • server_name _;: Will match any hostname used and redirect to HTTPS.

Conclusion

If you need any specific rules regarding Nginx don’t hesitate to put a comment below. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.