Redirect HTTP to HTTPS in Nginx

In this article I will give an example of setting up constant forwarding http requests to https.

For convenience, you can use one file to configure each site, for example, take the subdomain test.ixnfo.com, that is, at the beginning of each file we describe http:

server {
    listen 80;
    #listen [::]:80;
    server_name test.ixnfo.com;
    return 301 https://$server_name:443$request_uri;
}

In general, it looks something like this:

server {
    listen 80;
    #listen [::]:80;
    server_name test.ixnfo.com;
    return 301 https://$server_name:443$request_uri;
}

server {
   listen 443 ssl;
   #listen [::]:443 ssl;
   root /var/www/test;
   index index.php;
   access_log /var/log/nginx/test_access.log;
   error_log /var/log/nginx/test_error.log;
   server_name test.ixnfo.com;

   ssl_certificate ...
   ...

Or you can create only one file for http and redirect requests from all sites:

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

You can also create the configuration file /etc/nginx/sites-enabled/ip.conf, for redirecting http and https requests to a specific domain, if someone suddenly opens a server IP address in a browser, for example:

server {
    listen 80;
    #listen [::]:80;
    server_name 192.168.2.2;
    return 301 https://test.ixnfo.com:443$request_uri;
}

server {
    listen 443 ssl;
    #listen [::]:443 ssl;
    server_name 192.168.2.2;
    return 301 https://test.ixnfo.com:443$request_uri;
}

See also my articles:
How to disable TLS 1.0 and TLS 1.1 in Nginx
Install and configure Nginx

Leave a comment

Leave a Reply