Best way to setup HTTP to HTTPS redirect in NginX

Posted on Posted in NginX

When we install SSL certificate on the server and enable encryption for the website one of the steps we need to take is to confire redirect from http to https.

It is not a big dial if the website is running at Apache web server. The redirect rule in .htaccess looks like the following:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)${REQUEST_URI} [R,L]

There is a htacсess to NginX convert tool that returns the following code that needs to be inserted into the http configuration section:

# nginx configuration
location / {
  rewrite ^(.*)$$request_uri redirect;

But what if we are looking for the conditional redrect that can be used everywhere (ex. Plesk control panel). The following code reproduces the .htaccess conditional redirect:

if ($https !~ ^on$ ) {
	rewrite ^(.*)$$request_uri redirect;

Leave a Reply

Your email address will not be published. Required fields are marked *