How to redirect non-www to www HTTP / TLS /SSL traffic on Nginx

htt‮www//:sp‬.lautturi.com
How to redirect non-www to www HTTP / TLS /SSL traffic on Nginx

To redirect non-www traffic to www on Nginx, you can use the server_name and return directives in the server block of your Nginx configuration file.

Here is an example of how you can redirect non-www traffic to www on Nginx:

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

server {
    listen 80;
    server_name www.example.com;
    ...
}

In this example, the first server block listens for HTTP traffic on port 80 for the example.com domain. The return directive redirects all traffic to the www.example.com domain using the 301 HTTP status code, which indicates a permanent redirect.

The second server block listens for HTTP traffic on port 80 for the www.example.com domain and can be used to configure the rest of the server.

To redirect HTTPS traffic, you can add an additional server block with a listen directive that listens for TLS/SSL traffic on port 443:

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

server {
    listen 443 ssl;
    server_name www.example.com;
    ...
}
Created Time:2017-10-28 21:39:06  Author:lautturi