Nginx配置虚拟主机教程详解

作者:袖梨 2022-06-30

nginx可以使用server块来设置多个虚拟主机,在server段中用server_name和listen指令来绑定域名和端口。例如:

代码如下 复制代码

server {
listen 80;
server_name www.111com.net;

location / {
root hzhuti;
index index.html;
}
}


上述配置就是指定了一个虚拟主机www.111com.net。可能在某些nginx的版本中上述的配置并不能很好的工作,出现的情况是所有的请求都是由第一个server处理的,如果要配置多个我们只要在后再以server {}中间配置一样的即可了。

下面介绍配置二级域名

代码如下 复制代码

server {
# 根据你的需要,可以替换这个商品,建议端口为80
listen 80 [default|default_server]; #could also be 1.2.3.4:80

# 多个域名用空格分隔
server_name star.yourdomain.com *.yourdomain.com;
#web目录
root /PATH/TO/WEBROOT/$host;
#404错误,找不到页面转为404.html
error_page 404 errors/404.html;
#日记记录
access_log logs/star.yourdomain.com.access.log;
#首页索引,从左往右,越前面优化级越高
index index.php index.html index.htm;

# 提供静态文件
location ~* .(jpg|jpeg|gif|css|png|js|ico|html)$ {
access_log off;
expires max;
}
#让nginx运行php-fpm
location ~ .php$ {
include fastcgi_params;
fastcgi_intercept_errors on;
# By all means use a different server for the fcgi processes if you need to
fastcgi_pass 127.0.0.1:YOURFCGIPORTHERE;
}

location ~ /.ht {
deny all;
}
}

上面介绍的都是单主机了,如果我要配置双主机呢,下面看方法。


Nginx官网上说是做proxying without caching,但实际观察下来,似乎也是有cache的。实际上在同一时刻,外部来的HTTP连接数远大于proxy到varnish的连接数。

用Nginx虚拟主机的另一个考虑,也为以后访问量进一步增大后,可能需要增加的第二台缓存服务器做简单负载均衡的准备。

代码如下 复制代码

upstream mysite.cn {

server 127.0.0.1:8080 ;

# server 192.168.11.1:80; 今后可能的第二台cache

}

server

{


第一个虚拟主机,用于varnish和Nginx运行状态监测

代码如下 复制代码

listen 80;

server_name cache.mysite.cn;

index index.htm index.html index.php;

root /web/htdocs;

location / {

index infov.txt;

allow 192.168.0.0/16;

deny all;

}

location /status {

stub_status on;

access_log off;

allow 192.168.0.0/16;

deny all;

}

}

server

{


第二个虚拟主机,proxy到后面的varnish

代码如下 复制代码

listen 80;

client_max_body_size 50M;

server_name .mysite.cn;

index index.htm index.html index.php;

root /web/htdocs;

location / {

proxy_pass http://my*s*ite.c*n;

proxy_redirect off;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

client_max_body_size 50m;

client_body_buffer_size 256k;

proxy_connect_timeout 10;

proxy_send_timeout 15;

proxy_read_timeout 15;

proxy_buffer_size 4k;

proxy_buffers 4 32k;

proxy_busy_buffers_size 64k;

proxy_temp_file_write_size 64k;

}

#location ~ .*.php?$

#{

# include conf/fcgi.conf;

# fastcgi_pass 127.0.0.1:10080;

# fastcgi_index index.php;

#}

}

相关文章

精彩推荐