Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to the home page in nginx

I have the following nginx server block.

server {
    listen 80;
    server_name myapp.io www.myapp.io;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;

    server_name myapp.io www.myapp.io;

    ssl_certificate /etc/letsencrypt/live/myapp.io/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/myapp.io/privkey.pem;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:EC$
    ssl_session_timeout 1d;
    ssl_stapling on;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security max-age=15768000;

    location ~ /.well-known {
        allow all;
    }

    location / {
        proxy_set_header    Host                $host;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto   $scheme;
        proxy_set_header    Accept-Encoding     "";
        proxy_set_header    Proxy               "";
        proxy_pass          https://127.0.0.1:3000;

        # These three lines added as per https://github.com/socketio/socket.io/issues/1942 to remove sock$

        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection "upgrade";
    }
}

Now, I would like to do the following redirection:

  1. keep the redirection http://anything to https://anything

  2. redirect https://www.myapp.io or http://www.myapp.io to https://www.myapp.io/home

Does anyone know how to amend my server block to achieve this?

Edit 1: enter image description here

like image 920
SoftTimur Avatar asked Oct 24 '25 05:10

SoftTimur


1 Answers

You should add a location = / block to force the root URI to home. For example:

server {
    listen 443 ssl;

    server_name myapp.io www.myapp.io;

    ssl_certificate ...;
    ssl_certificate_key ...;
    ...

    location = / {
        return 301 /home;
    }

    location ~ /.well-known {
        allow all;
    }

    location / {
        proxy_set_header    Host                $host;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto   $scheme;
        proxy_set_header    Accept-Encoding     "";
        proxy_set_header    Proxy               "";
        proxy_pass          https://127.0.0.1:3000;

        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection "upgrade";
    }
}
like image 129
Richard Smith Avatar answered Oct 26 '25 18:10

Richard Smith