I'm new to Nginx, I want to block direct IP address access to my server and redirect wildcard domain to my main website. Here is why I got so far in /etc/nginx/sites-available/default
:
server {
listen 80;
listen [::]:80;
server_name ~^(www\.)?(?<domain>.+)$;
if ($domain != "12.13.14.15") {
return 301 https://mainwebsite.com/$domain;
}
return 404;
}
Everything seems to be working fine with the config above, but later I found that Nginx if is evil, also when the domain doesn't exist in my main website's database it will show 404 not found page on the mainwebsite.com.
What I'm trying to achieve are:
- Block direct IP address access without using
if
. - Redirect wildcard domain to my main website if the domain actually exists in my database, else return 404 without redirection. I noticed there is
try_files
but I'm not sure if it can be used to check an external URL.
Can someone please give me some light?