Skip to content

Nginx – The Best Way to Force Redirect to HTTPS with WWW URL

Nginx HTTPS Redirect Setup. Nginx, The Best Way to Force Redirect to HTTPS with WWW URL. Auto Redirect to https in Nginx with www prefix.

Category
Web Servers
Covers
Nginx, SSL/TLS
Versions & support
About Nginx →

Questions- How do I force redirect users to https with www prefix domain. How do I redirect a user to https in Nginx? The Best Way to Force Redirect Users to WWW and HTTPS.

This tutorial will provide you the best way to redirect users forcefully to https:// URL with www domain prefix. For example, your domain name is example.com, Below configuration will forcefully redirect users to https://www.example.com in all ways.

Let’s edit Nginx virtual host configuration file:

sudo vim /etc/nginx/sites-enabled/example.com.conf

and add the below content. change example.com with your actual domain name. Also, add any other required settings specific for your Virtual host.

# Force all users to https://www.example.com

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://www.example.com$request_uri;
}
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/nginx/ssl/www.example.com.pem;
    ssl_certificate_key /etc/nginx/ssl/www.example.com.key;
    return 301 https://www.example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.com;
    root /var/www/html
	
    error_page  403 /error/404.html;
    error_page  404 /error/404.html;
    error_page  500 502 503 504 /error/50x.html;

    ssl_certificate /etc/nginx/ssl/www.example.com.pem;
    ssl_certificate_key /etc/nginx/ssl/www.example.com.key;
}

After making the change to the configuration file, restart your Nginx web server and try to access your domain like URLs. In all the conditions, this will be redirected to https://www.example.com.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

8 Comments

  1. web in hml get error ngnix don’t restart, and if i install force_https templates too get error ngnix don’t restart

    this is an ngnix error?

    thanks

  2. Hello, what is the path of the file, Nginx virtual host, to edit and insert the information reported in your tutorial?
    Thank you very much.

Leave a Reply

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


Back to top