sslnginx

Trying to set Http to Https Redirect on Nginx


I have my server set up already and project deployed on Vultr VPS and i am trying to set redirection for my domain but i keep getting this error This page isn’t working henryestate.xyz redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS

I have tried to edit what my etc/nginx/sites-enabled/default

I have the below code:

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

  # SSL configuration
  #
  listen 443 ssl;
  # listen [::]:443 ssl default_server;
  #
  # Note: You should disable gzip for SSL traffic.
  # See: https://bugs.debian.org/773332
  #
  # Read up on ssl_ciphers to ensure a secure configuration.
  # See: https://bugs.debian.org/765782
  #
  # Self signed certs generated by the ssl-cert package
  # Don't use them in a production server!
  #
  # include snippets/snakeoil.conf;
  root /var/www/laravel/public;

  # Add index.php to the list if you are using PHP
  index index.php index.html index.htm;

  server_name henryestate.xyz www.henryestate.xyz;

  return 301 https://henryestate.xyz$request_uri;


  ssl_certificate /etc/nginx/ssl/cert_chain.crt;
  ssl_certificate_key /etc/nginx/ssl/server.key;

  location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ /index.php?$query_string;
  }

  # pass PHP scripts to FastCGI server
  #
  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    #
    # # With php-fpm (or other unix sockets):
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    # # With php-cgi (or other tcp sockets):
    # fastcgi_pass 127.0.0.1:9000;
  }

  # deny access to .htaccess files, if Apache's document root
  # concurs with nginx's one
  #
  location ~ /\.ht {
    deny all;
  }
}

How can i sort this https redirection to allow the website load with https for both www and non www


Solution

  • If you mean redirection from HTTP to HTTPS preserving the server name (www or non-www), use two distinct server blocks:

    server {
      listen 80 default_server;
      listen [::]:80 default_server;
      server_name henryestate.xyz www.henryestate.xyz;
      return 301 https://$host$request_uri;
    }
    
    server {
      listen 443 ssl;
      server_name henryestate.xyz www.henryestate.xyz;
      ...
    }
    

    Remove return 301 https://henryestate.xyz$request_uri; from the second server block.

    Instead of try_files $uri $uri/ /index.php?$query_string; it's better to use try_files $uri $uri/ /index.php$is_args$args;.