Nginx – Avoid double redirect NGINX

nginxredirectrewrite

I'm redirecting my website users to the HTTPS version of the site using a 301 redirect with Nginx.
I've tested my site using PageSpeed from Google and found that I was double redirecting from the main page. This is because of my CMS. Example:
http:// domain.tld -> NGINX 301 -> to https:// domain.tld -> CMS redirect -> https:// domain.tld/homepage

I was hoping that I could redirect the direct root link using NGINX with

location = / {
    return 301 https:// domain.tld/homepage;
}

this works for the home page, however, this will give 404 errors to any other http page than the homepage, I tried adding return 301 https://$host$request_uri; under the location block, but somehow this overwrites the root domain rule. (which give a double redirect again) Is there any way to redirect all links with their appropriate request_uri, EXCEPT for the root domain?

P.S. I was hoping to do this without an if function: See: https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

Here is a sample of my full config file:

server {
    listen       80;
    server_name  domainname.tld;

    location = / {
        return 301 https://domainname.tld/homepage;
    }

    return 301 https://$host$request_uri; 
    #if i remove this I'll get 404 errors on any other page than the homepage.
    #but if I add it, the 'location = /' block gets ignored.
}

server {

    listen 443 ssl;

    server_name domainname.tld;

    root /var/www/domainname.tld;
    index index.php;

    ... (stuff like rewrite rules, irrelevant) ...

}

Best Answer

Just wrap it in a location / { ... } block to give it equal precedence:

server {
    listen       80;
    server_name  domainname.tld;

    location = / {
        return 301 https://$server_name/homepage;
    }
    location / {
        return 301 https://$server_name$request_uri; 
    }
}

See this document for details.