0

Every subdomain is in a separate folder. I capture the subdomain and set the root to the correct folder with this code:

server_name ~^(?<sub>.+)\.mysite\.com$;
root "/path/to/my/site/$sub";

When the sub domain does not exist, it throws a 404 error, but not using my 404 error page because the root is set to a directory that does not exist.

I can solve the problem with this code:

server_name ~^(?<sub>.+)\.mysite\.com$;
if (!-d "/path/to/my/site/$sub") {
    set $sub www;
    #set $sub "";
}
root "/path/to/my/site/$sub";

but obviously, it is wrong because if is evil, or have I found an exception where it is correct of me to use if.

  • 1
    Why do you need to do it in the same server block? Use a catch-all server block. See this answer, but make the response anything you like. – Richard Smith Apr 22 '18 at 11:23
  • Why not use an error_page? – Michael Hampton Apr 22 '18 at 16:33
  • @MichaelHampton I have tried with error_page and it doesn't work. It only works if the error page is static, and it needs to be a .php file. – Dan Bray Apr 22 '18 at 20:00
  • But, a PHP file from which document root? – Michael Hampton Apr 22 '18 at 23:41
0

There was a problem with the code for my error page. That now works, which has allowed me to fix a different problem (extensionless php with redirects).

error_page 404 =200 /404.php;    
location = /404 {
    #root "/path/to/404/page";
}

I tried setting the root inside location = /404 but that does not work. I have found no way to avoid the if statement and still make it work correctly.

if (!-d "/path/to/my/site/$sub") {
    return 301 https://www.example.com$request_uri;
}

I guess it's better to have a very small amount of if statements for redirects, than to have a broken website.

Even Plesk Onyx's auto generated code used an if statement:

if ($host ~* ^example\.com$) {
    return 301 https://www.$host$request_uri;
}

However, I would still prefer to avoid if statements altogether, if i can get my site to work 100% correctly without them.

| improve this answer | |

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.