Nginx ignoring server_name
I have a website running on an Nginx web server which runs over HTTPS. I noticed recently that someone has pointed their domain to my web server and Nginx is serving my website to this bad domain. It looks like it's even indexing in google...
Nginx config:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com/ssl-bundle.crt;
ssl_certificate_key /etc/nginx/ssl/example.com/example.com.key;
root /var/www/example.com;
index index.html;
}
I have tried adding an if
statement to check if the $host
matches the server_name
as recommended here
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com/ssl-bundle.crt;
ssl_certificate_key /etc/nginx/ssl/example.com/example.com.key;
# Check if incoming hostname matches server_name
if ($host != $server_name) {
# If not, return 404
return 404;
}
root /var/www/example.com;
index index.html;
}
This addition didn't seem to help. Is any of this on the right track? Any suggestions would be much appreciated
Solution 1:
I have a website running on an Nginx web server which runs over HTTPS. I noticed recently that someone has pointed their domain to my web server and Nginx is serving my website to this bad domain. It looks like it's even indexing in google...
The best way to deal with this or a similar situation is to create a default catchall server block. For example, here's what I have to serve other domains that are pointed towards my server's IP.
server {
listen 80 default_server;
server_name _;
# deny all
location / {
return 403;
}
}
I hope that helps!
Solution 2:
Creating a catch-all server would be the best option. You could either return 404;
, as suggested, or redirect everything to the canonical hostname; that'd solve the problem with search engines.
Here's my alternative with a complete configuration:
server {
# catch-all server for both http and https
listen *:80 default_server;
listen *:443 default_server;
server_name _;
# Your SSL configuration
ssl_certificate /etc/nginx/ssl/example.com/ssl-bundle.crt;
ssl_certificate_key /etc/nginx/ssl/example.com/example.com.key;
# Redirect to canonical site
rewrite ^/(.*)$ http://example.com/$1 permanent;
}