How to Redirect HTTP to HTTPS in Nginx With HTTP/301 Code

 Thanks to: https://www.cyberciti.biz/

Ihave setup nginx as a secure reverse proxy server. How do I redirect all http://example.com/ requests (traffic) to https://example.com/ under nginx web server? How do I configure Nginx to redirect HTTP To HTTPS?


You can easily rewrite/redirect all http requests to https with Nginx web server. The syntax is as follows. You need to add the following in location or server directives. This quick guide explain how to redirect the HTTP traffic to HTTPS in Nginx.

Nginx Redirect HTTP To HTTPS

Now that you configured and installed an SSL certificate for Nginx, it is time to drop all HTTP traffic and send users to HTTPS version. Edit nginx.conf file:
sudo vi /etc/nginx/nginx.conf

if ($host ~* ^(example\.com|www\.example\.com)$ ){
  rewrite  ^/(.*)$  https://example.com/$1  permanent;
}

OR better use the following rewrite:

rewrite  ^ https://$server_name$request_uri? permanent;

Or use new syntax (recommended):

return         301 https://$server_name$request_uri;

Redirecting all HTTP requests to HTTPS with Nginx server

Edit your nginx.conf file, enter:
# vi nginx.conf
You need to define both http and https server as follows:

################################
## our HTTP server at port 80 ##
################################
server {
      listen      80 default;
      ## set up domain name here ##
      server_name www.cyberciti.biz cyberciti.biz
      access_log off;
      error_log off;
      ##** nginx redirect ALL http requests to https ** ##
      return      301 https://$server_name$request_uri;
}
#########################################################################
## Our HTTPS server at port 443. You need to provide ssl config below ###
#########################################################################
server {
      access_log  logs/cyberciti.biz/ssl_access.log main;
      error_log   logs/cyberciti.biz/ssl_error.log;
      index       index.html;
      root        /usr/local/nginx/html;
      ## start ssl config ##
      listen      443 http2 ssl;
      server_name www.cyberciti.biz cyberciti.biz
 
     ## redirect www to nowww
      if ($host = 'www.cyberciti.biz' ) {
         rewrite  ^/(.*)$  https://cyberciti.biz/$1  permanent;
      }
 
    ### ssl config - customize as per your setup ###
     ssl_certificate      ssl/cyberciti.biz/cyberciti.biz_combined.crt;
     ssl_certificate_key  ssl/cyberciti.biz/cyberciti.biz.key_without_password;
     ssl_protocols        TLSv1 TLSv1.1 TLSv1.2;
     keepalive_timeout    70;
     ssl_session_cache    shared:SSL:10m;
     ssl_session_timeout  10m;
    ### Rest of my config. It is optional. Do it only if you have Apache on backend ## 
 
    ## PROXY backend 
      location / {
        add_header           Front-End-Https    on;
        add_header  Cache-Control "public, must-revalidate";
        add_header Strict-Transport-Security "max-age=2592000; includeSubdomains";
        proxy_pass  http://cybercitiproxy;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      }
}

Save and close the file. Reload or restart the nginx server:
# nginx -s reload
Test it:
$ curl -I http://cyberciti.biz
$ curl -I http://cyberciti.biz/foo/bar/file.html

Sample outputs:

Nginx Redirect HTTP To HTTPS

Fig.01 Rewrite 301 HTTP to HTTPS in Nginx server

Redirect All HTTP traffic

Edit or append as follows in your nginx.conf:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

The return directive stops processing and returns the specified code to a client. The non-standard code 444 closes a connection without sending a response header. In above example, we are returning HTTP code 301:
return code URL;
return 301 URL;
return 301 URL;

One can use the following code:

  • HTTP/301 – The HTTP response status code 301 Moved Permanently is used for permanent URL redirection
  • HTTP/302 – The HTTP response status code 302 Found is a common way of performing URL redirection with Moved Temporarily code.

In addition, a URL for temporary redirect with the code 302 can be specified as the sole parameter. Such a parameter should start with the “http://”, “https://”, or “$scheme” string. A URL can contain variables.

Comentarios

Entradas populares de este blog

Guía de herramientas básicas para estudiantes: 31 apps y webs imprescindibles para ayudarte con los estudios

Comando FOR para archivos BAT

How to Setup and Configure Your Own GitLab Server on Ubuntu 20.04