Redirect All HTTP Requests to HTTPS for Nginx

nginx redirect http to https

To add redirect for all HTTP requests to HTTPS, we need to add Nginx Redirect rules to the nginx config file.
The server block for http requests should look like :

## our http server at port 80
server {
      listen      1.2.3.4:80 default;
      server_name example.com www.example.com;
      ## redirect http to https ##
      rewrite        ^ https://$server_name$request_uri? permanent;
}

You should have another Server block for https requests, which shoudl look like :

## Our https server at port 443. You need to provide ssl config here###
server {
      access_log  logs/example.com/ssl_access.log main;
      error_log   logs/example.com/ssl_error.log;
      index       index.html;
      root        /usr/local/nginx/html;
      ## start ssl config ##
      listen      1.2.3.4:443 ssl;
      server_name example.com www.example.com;
 
     ## redirect www to nowww
      if ($host = 'www.example.com' ) {
         rewrite  ^/(.*)$  https://example.com/$1  permanent;
      }
 
    ### ssl config - customize as per your setup ###
     ssl_certificate      path/to/ssl/certificate.crt;
     ssl_certificate_key  path/to/certificate/private.key
     ssl_protocols        SSLv3 TLSv1 TLSv1.1 TLSv1.2;
     ssl_ciphers RC4:HIGH:!aNULL:!MD5;
     ssl_prefer_server_ciphers on;
     keepalive_timeout    70;
     ssl_session_cache    shared:SSL:10m;
     ssl_session_timeout  10m;
 
    ## 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://exampleproxy;
        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;
      }
}
 

After making the changes in Nginx, test the new Nginx config by running the following command :

nginx -t

If this does not show any errors, restart nginx to bring the changes into effect :

service nginx restart
WPOven
© 2024 WPOven Inc. All rights reserved. WPOven® and WordPress® are registered trademarks.
WPOven is the best Managed WordPress hosting for agencies and businesses that want to succeed. With Unlimited sites hosting option, its easy to use and manage, so you can focus on growing your business. 
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram