Table of Contents

Nginx Configuration Examples

Nginx Sample Configuration of Rewrite and return



'retrun' is recommended rather than 'rewrite'.


How to use return

/etc/nginx/conf.d/example.conf

redirect from http(port 80) to https(port443)

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

server {
    listen 443 ssl;
    .
    .
    .
}


From www.example.com To example.com

# http://www.example.com  --> https://example.com
server {
    listen 80;
    server_name  www.example.com;
    return 301 https://example.com$request_uri;
}

# https://www.example.com  --> https://example.com
server {
    listen   443 ssl http2;
    server_name  www.example.com;

    ssl on;
    ssl_certificate      /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/www.example.com/privkey.pem;
    return 301 https://example.com$request_uri;
}


# http://example.com  --> https://example.com
server {
    listen 80;
    server_name  example.com;
    return 301 https://$host$request_uri;
}

server {
    listen   443 ssl http2;
    server_name  example.com;

    ssl on;
    ssl_certificate      /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/example.com/privkey.pem;
    
    .
    .
}




How to use rewrite

redirect from http(port 80) to https(port443)

server {
    listen 80;
    server_name  www.example.com  example.com;
    if ($http_host = example.com) {
        rewrite  (.*)  http://www.example.com$1  permanent;
    }
    .
    .
}