NGinx Ubuntu How to redirect http to https?

OS type and version Ubuntu 20.04
Webmin version 1.991
Virtualmin version 7.0-4 Pro
Related packages NGinx Server

Hi, I have been trying to redirect http traffic to https but struggling with it.

I went to virtualmin server → systems settings → virtualmin configuration → ssl settings → and selected redirect http to https to YES. It did nothing even after I restarted entire server after this change.

I also went to Webmin → NGinx Web Server → Selected Server → Went to URL Re-Writing and set http:// to redirect to https:// saved and applied NGinx configuration.

It did nothing. http:// traffic still going to http:// only. So checked and found that the rewrite entry was under listen ip:443 ssl; So moved that rewrite entry to go under listen ip; but that also didn’t do anything.
I also tryed to instead of just http:// to https:// but that also didn’t do anything.

From internet everyone is saying just one thing. Use following code in NGinx configuration and it should work fine.

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

I tried as it is in /etc/NGinx/NGinx.conf and even in /etc/NGinx/Sites-Available/ but most times system kept giving errors of invalid configuration when I applied NGinx configuration in webmin. And where configuration was accepted it did nothing and traffic was still going to http://

The only thing that did something was when in file when I added following line under listen ip; then redirection started working. However page loading stoped saying too many redirects.

return 301$request_uri;

At this stage I am thinking it must not be that hard what is a basic requirement of almost all sites with SSL. (in case of PHP website it was as easy as just updating .htaccess and it worked just fine) So thought to check with you if you can advise something that can help resolve this.

Hi again,

if ($scheme = “http”) {
return 301$request_uri;

instead of

    return 301$request_uri;

fixed the issue finally. I had to manually configure /etc/nginx/sites-available/ adding the if loop under listen ip; and now it is redirecting fine. I tried $http_x_forwarded_proto first which also did not work so on one suggestion of $scheme replacing it worked fine. Whatever that is.

Provided detail above thinking this may help someone.

This topic was automatically closed 8 days after the last reply. New replies are no longer allowed.