How to redirect https://www to non-www https version in nginx?

by arnoldo.moen , in category: Third Party Scripts , a month ago

How to redirect https://www to non-www https version in nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , a month ago

@arnoldo.moen 

To redirect https://www to the non-www https version in Nginx, you can add the following server block configuration to your Nginx configuration file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
server {
    listen 443 ssl;
    server_name www.example.com;

    ssl_certificate /path/to/ssl/certificate;
    ssl_certificate_key /path/to/ssl/private/key;

    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /path/to/ssl/certificate;
    ssl_certificate_key /path/to/ssl/private/key;

    # Your server configuration goes here
}


In this configuration, the first server block listens for requests on the www domain and redirects them to the non-www version using a 301 redirect. The second server block listens for requests on the non-www domain and serves the actual content of your website.


Make sure to replace www.example.com and example.com with your actual domain name, and replace /path/to/ssl/certificate and /path/to/ssl/private/key with the paths to your SSL certificate and private key files.


After making these changes, don't forget to restart Nginx for the changes to take effect.