0

I build a website with Google domain on the Nginx server. I want to redirect all links to secure and non www link. For example:

http://example.com       ->  https://example.com
http://www.example.com   ->  https://example.com
https://www.example.com  ->  https://example.com

Whenever I access to site, the page says redirected you too many times.

Here is my nginx.conf

###### Redirect to secure site
server {
  listen       80;
  listen       [::]:80;
  server_name example.com www.example.com;
  return 301 https://example.com$request_uri;
}

###### Redirect to non www site
server {
  listen [::]:443 ssl http2;
  listen 443 ssl http2;

  server_name www.example.com;

  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

  return 301 https://example.com$request_uri;
}

###### Main config for secure and non www site
server {
  listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot
  listen 443 http2 ssl;

  server_name example.com;

  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

  root /usr/share/nginx/example.com;
}
4
  • Your config looks alright. However the 301 Moved Permanently redirects are cached by the browser, so he might follow an old redirect. Restart your browser to clear the cache. Feb 26, 2020 at 10:31
  • Thank Piotr P. Karwasz but does the domain setting conflict in this case? For example, the www Name should be A type instead of CNAME type?
    – quyleanh
    Feb 26, 2020 at 10:49
  • Whether www.example.com is a CNAME or A record doesn't matter. If it isn't a problem with your browser (which cached a redirection loop from a previous config), maybe you didn't reload nginx after the change. You can debug the problem with curl -i. Feb 26, 2020 at 11:00
  • Thank you but even when I clear cache, cookies and close browser, the redirect loop still happens... What should I do now?
    – quyleanh
    Feb 26, 2020 at 12:09

1 Answer 1

1

It's turned out that I have mistake on setting WordPress Address (URL). I have set to www.example.com instead of example.com. When I correct URL address, everything is fine now.

There is no problem with nginx.conf.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .