How to redirect from http://www.* to https://* in nginx?

Member

by jasen , in category: Third Party Scripts , 6 months ago

How to redirect from http://www.* to https://* in nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 6 months ago

@jasen 

To redirect from HTTP to HTTPS in Nginx, you can add a server block in your Nginx configuration file. Here is an example of how to redirect from http://www.example.com to https://example.com:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;
    # SSL configuration goes here
    ...
}


In this configuration, the first server block listens on port 80 for requests to www.example.com and redirects them to https://example.com using a 301 (permanent) redirect. The second server block listens on port 443 for requests to example.com and handles the HTTPS traffic.


Make sure to replace example.com with your actual domain name and update the SSL configuration in the second server block as needed. After making these changes, reload Nginx to apply the new configuration.

Related Threads:

How to redirect https://www to non-www https version in nginx?
How to redirect http to https and https://www to https://?
How to permanently redirect `http://` and `www.` urls to `https://`?
How to redirect http to https in nginx/1.18.0 ubuntu?
How to force redirect a subdomain to 'https://www.'?
How to redirect ip to https domain in nginx?