0

I just installed Let's Encrypt wildcard certificate and I want to use the non www as my standard regex for shorter server block. So I wish to do the following:

  1. http non www ---> https non www

  2. http www ---> https non www

  3. https www ---> https non www

  4. http any ---> https any to a specific folder for example /var/www/any

  5. https any ---> https any to a specific folder for example /var/www/any

Am I doing this right? Are there too many redirections? I hope you get what I want achieve here.

  • what have you tried and what were the results? – user16081-JoeT Jan 29 at 1:24
  • @user16081-JoeT hi, i have successfully solved my problem as you can see below... but someone may edit the answer if necessary... i didn't use regex because i read somewhere avoid using if statement in nginx due to the if is evil stuff... – sudoranger Jan 30 at 20:58
0

I found the answer already after doing some tests...

# case 1 & 2...

server {
    listen 80;
    listen [::]:80;
    server_name <domain> www.<domain>;
    return 301 https://<domain>$request_uri;
}

# case 3...

server {
    listen 443 http2 ssl;
    listen [::]:443 http2 ssl;
    server_name www.<domain>;
    ...
    return 301 https://<domain>$request_uri;
}

# the main server block...

server {
    listen 443 http2 ssl;
    listen [::]:443 http2 ssl;
    ...
}

For case 4 & 5, I first need to add a subdomain via CNAME record in my DNS and point it to my primary domain then create a server block with the root folder corresponding to the server_name (the subdomain) that you want.

server {
    ...
    server_name <subdomain>.<domain>
    root /var/www/any
    ...
}

Also worth mention (to avoid domain parking and domain not related to the IP) and return a "444 Connection Closed Without Response"...

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    access_log off;
    log_not_found off;
    server_name _;
    return 444;
}

A reference about not using regex redirection and avoid if statement: https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.