server_name의 역할 #
nginx는 같은 포트를 listen하는 여러 개의 사이트를 있게 할 수 있는데,
여기서 server_name은 하나의 포트를 listen 하고 있는 여러 개의 사이트가 있을 때 어느 쪽을 사용할지 결정해주는 역할을 한다.
만약 server_name에 일치하는 것이 없다면 default_server가 있는 것이 우선적으로 사용되고 default_server 붙은 것이 없다면 먼저 선언한 것이 우선한다.
이걸 응용하면 웹사이트에 특정 주소로 접속하는 것을 허용하거나 막을 수 있다.
문법 #
http의 server 블록에서
listen 포트 default_server;
server_name 주소;
server {
listen 80 default_server;
server_name a.example,com;
root /var/www/html;
index index.html;
}
예제 #
IP주소로 접근하는 것을 막기 #
server {
listen 80;
charset utf-8;
server_name a.example,com;
root /var/www/html;
index index.html;
}
server {
listen 180 default_server;
return 444;
}
지정한 주소 이외의 방법으로 접속하는 것을 막고싶다면 가장 우선적으로 사용하는 default_server붙은 곳에 444 응답을 반환하게 하면 된다.
이렇게 default_server 에서는 444를 반환하고 사이트의 server_name을 a.example,com로 지정하면 a.example,com 이외의 방법으로 사이트를 접속하게 되면 444를 반환하게 된다.
444는 표준 HTTP응답 코드는 아니고 무응답을 의미하는 nginx의 응답인데 403같은 다른 반환을 넣어도 크게 상관은 없다.
localhost, 127.0.0.1로만 접속할 수 있게 하기 #
server {
listen 80;
charset utf-8;
server_name localhost 127.0.0.1;
root /var/www/html;
index index.html;
}
server {
listen 80 default_server;
return 403;
}
하나의 포트로 여러 개의 사이트 #
server {
listen 80;
charset utf-8;
server_name localhost;
root /var/www/html1;
index index.html;
}
server {
listen 80;
charset utf-8;
server_name 127.0.0.1;
root /var/www/html2;
index index.html;
}
localhost로 들어 갈 때는 root가 /var/www/html1 127.0.0.1로 들어갈 때는 root가 /var/www/html2 가 되게 하기
server {
listen 80;
charset utf-8;
server_name a.example.com;
root /var/www/a;
index index.html;
}
server {
listen 80;
charset utf-8;
server_name b.example.com;
root /var/www/html;
index index.html;
}
server {
listen 80;
charset utf-8;
server_name c.example.com;
root /var/www/html;
index index.html;
}
server {
listen 80 default_server;
return 444;
}
a.example.com, b.example.com, c.example.com 으로 접속할 때 각각 다른 사이트로 연결되게 하고 그 이외의 방법으로 접속하면 서버가 아무 것도 전송하지 않기.
a.example.com, b.example.com, c.example.com 도메인을 전부 같은 IP로 향하게 하면 된다.
기타 #
그런데 이건 TLS인증을 쓰지 않은 경우라 TLS를 적용한다면 내용이 조금 달리질 수도 있을 것 같다. 비슷한 nginx 문서
Reply by Email