Nginx rewrite or redirect for subfolder

nginxredirectrewrite

I have a Debian 10 server with NGINX. And it is servering several domains. Let me explain the situation:

  • I have setup my HTTP redirects permanently to HTTPS, in a file called redirect.conf. It is responsible for redirecting for all http to https domains. That works beautifully. So if anyone goest to http://host.domain.com it redirects to https://host.domain.com. NO PROBLEMS there.
  • I am now trying to setup a secondary redirection to subfolder, for only ONE SPECIFIC DOMAIN, but that keeps failing. The browser keeps telling me too many redirects.

I would very much like the following to happen:

  1. In browser you type the URL ==> http://host.domain.com OR https://host.domain.com
  2. You get redirected to https://host.domain.com (WORKS GREAT)
  3. Further redirects to https://host.domain.com/subfolder (FAILS HERE – Browsers complaint too many redirects).

Is there a better way of doing this? As I said in (1) above, whether you enter http or https, I would like the end result for that particular domain to go to /subfolder.

Here is my code for specific domain redirect to subfolder host-domain.conf:

server {
  ssl_certificate /etc/ssl/cert.pem;
  ssl_certificate_key /etc/ssl/key.pem;
  index index.php index.html;
  client_max_body_size 0;
  root /web;
  server_name host.domain.com;

 location / {
    return 301 https://host.domain.com/subfolder/;
  }

}

Best Answer

Something like this:

location / {
  return 301 https://host.domain.com/subfolder$uri;
}

location /subfolder/ {
  try_files $uri $uri/index.html $uri.html =404;
}