Home > Back-end >  Redirect www https site to non-www https cause too many redirect in nginx
Redirect www https site to non-www https cause too many redirect in nginx

Time:04-19

I have a project in Laravel, I am using digital ocean with nginx, I try to redirect www to non-www urls but I can't, this is my nginx configuration:

example.com

 server{
  listen 80;
  listen [::]:80;
  server_name example.com www.example.com;
  return 301 https://$host$request_uri;
}

server{

   listen [::]:443 ssl;
   listen 443 ssl;
   server_name www.example.com;

    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.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://$host$request_uri;

}

server {

  listen [::]:443 ssl;
  listen 443 ssl;
  server_name example.com;

  root /var/www/website/production/public;
  index index.php index.html;

  charset utf-8;

  location / {
     try_files $uri $uri/ /index.php?$query_string;
  }

  error_page 404 /index.php;

  location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    include fastcgi_params;
  }
    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

}

https://example.com //works

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

http://www.example.com -> https://www.example.com // redirects to www https, with too many redirects

https://www.example.com // too many redirects.

I want that when people visits http://www.example.com,http://example.com and https://www.example.com it redirects to https://example.com, What can I do? thanks.

CodePudding user response:

The second server block contains a loop:

server{
    listen [::]:443 ssl;
    listen 443 ssl;
    ...
    return 301 https://$host$request_uri;
}

The value of $host is the same as the requested domain. The purpose of this block is to change the requested domain from www.example.com to example.com.

The simplest solution is to change the return statement and explicitly specify the final domain name:

return 301 https://example.com$request_uri;
  • Related