1

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) ...

}
  • Giving 404 means it redirects you to a wrong URL. What is the wrong URL that you are being redirected to? – Florin Asăvoaie Sep 14 '16 at 12:09
  • Sorry, I didn't specify this clearly. It gives a 404 to ANY http link because http has no root folder added in the server block. I'll add this to my question. – StackerStan Sep 14 '16 at 12:30
0

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.

  • This worked! I combined this with the 302 redirect from coladict answer. Thanks! – StackerStan Sep 14 '16 at 13:35
0

You can use a regular expression to match only the root url, like this.

    location ~ ^/$ {
        return 301 https://domainname.tld/homepage;
    }

However, it is a better to keep it with a 301 code redirecting just to the HTTPS site, and a 302 code from the HTTPS site root to /homepage. You don't want search engines caching a 301 permanent redirect. It's a bad idea, because that page is likely to eventually change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.