在我们发布项目的时候,常常会有这样的需求,只有一台服务器,但是需要给这服务器绑定多个名域名。那我们该如何去解决这个问题呢。
我们可以使用nginx反向代理为这些域名建立映射,域名与端口号去建立映射。比如:www.aaa.com映射到192.168.12.4这台主机的8080端口号上,www.bbb.com映射到192.168.12.4这台主机的8081端口号上。所以让这两个域名都使用80端口号去访问nginx服务器,nginx服务器去访问对应端口号的应用程序。最后返回结果给客户端,其核心思想是隐藏了服务端。
我使用的web服务器是phpStudy。首先修改phpStudy的默认端口号为8081,然后在ngix中配置8081这个端口号。
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server
{
listen 80;
server_name www.aaa.cn;
root "C:/phpStudy/PHPTutorial/WWW";
location / {
proxy_pass http://127.0.0.1:8082;
index index.html index.htm index.php l.php;
autoindex off;
}
#access_log logs/nagios.xxx123.tk_access.log;
}
server
{
listen 80;
server_name www.bbb.cn;
root "C:/phpStudy/PHPTutorial/fr/WWW";
location / {
proxy_pass http://127.0.0.1:8081;
index index.html index.htm index.php l.php;
autoindex off;
}
#access_log logs/nagios.xxx123.tk_access.log;
}
}
每个server配置对应一个映射,域名对应这端口号。
我们也可以使用一个域名映射到多个主机,代理服务器,这样就可以做到负载均衡,用户的请求可以通过nginx分发到多台主机。