Redirect URL with HTTPS and WWW in NGINX



In this tutorial, we will understand, how to redirect any URL request with HTTPS and WWW using NGINX web server.

What is NGINX?

NGINX is a powerful web server and can be used as a reverse proxy, load balancer, and handling the web server cache.

Need of HTTP to HTTPS redirection?

When you are serving your content over HTTP, usually the connection is established between the client(maybe a web browser, mobile app, etc.) with your server, in case you are serving the content over the HTTP, there is a high chance that your connection with client communication will be intercepted and tampered by the attackers, hence it's best practice to always serve your content over HTTPS protocol.

Configure NGINX server block for HTTP to HTTPS redirection

Whenever any request comes with an HTTP block the Nginx server block will be executed with the port you are configured, assuming you are using the default port 80, you can add the rewrite statement inside the server block as below

server {
  listen 80;
  listen [::]:80;
  server_name domain.com www.domain.com;
  rewrite ^ https://$server_name$request_uri? permanent;
}

From the above code, you can understand that, whenever the request comes with port 80 for the HTTP protocol, we are redirecting the incoming request permanently with HTTPS, hence now the NGINX will search for the server block with port 443, let's move on to the next block of the configuration.

Configure to redirect incoming request with WWW

Below configuration will be executed by NGINX as soon as we redirect the request with HTTPS, you can see that we added the condition to check, if the request comes without www, then we will return the incoming request with www and since we need to serve the content with HTTPS, we need to configure the path for ssl certicates with ssl_certificate and ssl_certificate_key

server {
  listen 443 default_server ssl http2;
  server_name domain.com www.domain.com;
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
  if ($host = 'domain.com') {
    return 301 https://www.domain.com$request_uri;
  }

  ssl_certificate /etc/nginx/ssl_certificates/domain.com.chained.crt;
  ssl_certificate_key /etc/nginx/ssl_certificates/domain.com.key;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_prefer_server_ciphers on;
  ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

}

With above configuration placed inside the NGINX conf, you will be able to redirect any incoming request with HTTPS and WWW.

0
0