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?
http://domain.tld
orhttp://11.12.13.14
.server
block for that. Do not edit it; put the configuration for your own web site into a separateserver
block./etc/nginx/sites-available/mainwebsite.com
, my website is a platform for selling domain names, when I list a domain, I need to point that domain to my server IP address so when people visit the domain e.g.http://domainforsale.tld
they get redirected tohttps://mainwebsite.com/domainforsale.tld
and in other case, if the domain is already pointed to my server IP address but it's not listed yet on the main website give them 404 Nginx error instead.if
s evil? The article you referenced states that "it’s also possible to move ifs to server level (where it’s safe as only other rewrite module directives are allowed within it)." Since you're using theif
atserver
level, it is safe to do so.