zulhfreelancer
5/9/2017 - 5:30 AM

How to configure SSL and force HTTP to HTTPS redirection on Nginx for sub-domain?

How to configure SSL and force HTTP to HTTPS redirection on Nginx for sub-domain?

Nginx

Create a file named sub.domain-example.com in /etc/nginx/sites-available directory.

server {
       listen         80;
       server_name    sub.domain-example.com;
       return         301 https://$server_name$request_uri;
}

server {
        listen 443 ssl;

        # add Strict-Transport-Security to prevent man in the middle attacks
        add_header Strict-Transport-Security "max-age=31536000";

        root /var/www/sub.domain-example.com;
        index index.html index.htm index.nginx-debian.html;

        server_name sub.domain-example.com;

        location / {
                try_files $uri $uri/ =404;
        }

        ssl on;
        ssl_certificate /etc/nginx/ssl/sub.domain-example.com/sub.domain-example.com.crt;
        ssl_certificate_key /etc/nginx/ssl/sub.domain-example.com/sub.domain-example.com.key;
}

Don't forget to restart Nginx service by running:

service nginx restart

References