Nginx 多站点 vhost 配置原理
若需在 Linux 环境的 Nginx 服务器中通过不同域名分别访问特定的网站目录,则需要配置多个虚拟主机(vhost)。以下以将网站根目录统一设置在 /var/www/ 为例,介绍具体的配置流程。
首先,需要在 /var/www/ 目录下分别为各个站点新建独立的子目录,用于存放对应的网站文件。
/var/www/ushark.net
/var/www/ushark.wang
接着,编辑主配置文件 /etc/nginx/nginx.conf。
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf; #主要是加入此行,如有则忽略
}
然后,在 /etc/nginx/conf.d/ 目录下为每个站点新建对应的 .conf 配置文件。
/etc/nginx/conf.d/ushark.net.conf
/etc/nginx/conf.d/ushark.wang.conf
将标准的 Server 块配置信息复制到上述新建的两个文件中。关键操作是修改红色标注部分的内容,务必确保 server_name(域名)与 root(网站根目录)保持一致,从而实现域名与目录的一一对应关系。
server {
listen 80;
server_name www.ushark.net;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
root /var/www/ushark.net/;
if (!-e $request_filename){ # rewrite可根据网站需要增删
rewrite ^/(.*) /index.php last;
}
location / {
index index.php index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/ushark.net/;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~* \.php$ {
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
完成所有配置文件修改后,执行命令重启 Nginx 服务以使配置生效。
systemctl restart nginx
最后,编辑 /etc/hosts 文件。这是本地测试的核心步骤,用于将域名映射到本地 IP 地址。
[root@bogon ~]# vi 127.0.0.1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6
127.0.0.1 www.ushark.net
127.0.0.1 www.ushark.wang
总结
以上所述是小编给大家介绍的Nginx 配置多站点vhost 的方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!