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

Member

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

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 2 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.