En Jinex
En Jinex

Reputation: 1

Nginx keeps redirecting infinitely

I've followed the instructions from here on setting up nginx to redirect all non-www requests into www but I keep getting ERR_TOO_MANY_REDIRECTS in my browser when I try to hit any page.

My goal is twofold:

  1. All requests that don't have www should be redirected to www
  2. All requests that aren't HTTPS should be redirected to HTTPS

My nginx config looks like this:

upstream mywebsite_proxy {
  server unix:/home/deploy/mywebsite/tmp/sockets/puma.sock;
}

server {
  listen   80;
  listen   [::]:80;
  listen   443 default_server ssl;

  server_name www.mywebsite.com;

  if ($scheme = http) {
    return 301 https://$server_name$request_uri;
  }

  location / {
    proxy_pass http://mywebsite_proxy;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  location ~ ^/(robots.txt|sitemap.xml.gz)/  {
    root /home/deploy/mywebsite/public;
  }
}

Notice that there isn't any reference to SSL certificates. I'm using Cloudflare with SSL enabled and HTTPS seemed to just work right out the gate when my config looked like the one below. The non-www to www and non http to https redirects obviously didn't work though...

upstream mywebsite_proxy {
  server unix:/home/deploy/mywebsite/tmp/sockets/puma.sock;
}

server {
  listen 80;
  listen 443;
  server_name www.mywebsite.com mywebsite.com;
  root /home/deploy/mywebsite/public;

  location / {
    proxy_pass http://mywebsite_proxy;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  location ~ ^/(robots.txt|sitemap.xml.gz)/  {
    root /home/deploy/mywebsite/public;
  }
}

Upvotes: 0

Views: 1902

Answers (2)

dsax7
dsax7

Reputation: 1343

In my opinion you do not need the if part in:

if ($scheme = http) {
    return 301 https://$server_name$request_uri;
  }

The redirect should look like this:

    return 301 https://$server_name$request_uri;

Use 301 if you want to do a permanent redirect, which will be stored in the cache of your browser or 302 if you do not want it to be permanent. Furthermore, you can remove the www. part in the server_name and use return 301 https://www.$server_name$request_uri;

Upvotes: 1

faizulhaque
faizulhaque

Reputation: 106

I did some thing similar in one of my previous project, here are the steps:

  1. Left default config 'nginx.conf' as it is.
  2. modified /etc/nginx/sites-available/default (Gist: https://gist.github.com/faizulhaque-tp/db576dc6f22c820a0e23f7a6e1c8b740)

Apart from non-www to www, above configuration works.

Upvotes: 0

Related Questions