nginx 配置文件主要分为六个区域:php
main
: 全局设置html
events
: nginx工做模式nginx
http
: http设置浏览器
sever
: 主机设置服务器
location
: URL 匹配负载均衡
upstream
: 负载均衡服务器设置网站
下面,就以在 Windows 上使用 phpStudy 集成开发环境举例说明下 Nginx 的虚拟目录和虚拟主机是如何配置的:code
通俗地讲,虚拟目录的意思就是浏览器上输入的 URL 不必定就表明网站在文件系统中的绝对路径,而是能够在硬盘中的任意指定位置。orm
好比在浏览器上访问的是 http://localhost/test
,在网站根目录 C:/htdocs/ 下不必定就有 test 这个目录,而是能够在其余位置, 好比 d:/not_test。server
找到并打开 nginx.conf,而后在 location ~ //.ht {...}
字样下面添加便可:
1
2
3
4
5
|
location /test {
alias "C:/Users/cjli/PhpstormProjects/test";
index index.php;
autoindex on;
}
|
这里 /test
中的 test 是一个别名( alias ),能够自定义,而 alias
指令后面跟的路径也能够随意指向文件系统中任何存在的目录。
重启 Nginx 后打开 http://localhost/test 就能够看到上面目录 C:/Users/cjli/PhpstormProjects/test 下的网站了( 若是有的话 )。
虚拟目录路径的配置不能用 root
指令而必须用 alias
指令。
路径必须用双引号括起来。
index
指令和 autoindex
指令必须同时出现。
通俗地讲,虚拟主机的意思就是,功能上力求和一台物理机实现得一致。
所以就很容易解释为何多个虚拟主机中能够监听同一个端口号这样的问题了,由于虽然端口号是相同的,可是能够理解为是不一样个主机上的同一个端口,这固然不影响了。
为了管理方便,对 Nginx 的配置文件均可以放在一个文件夹下,而后统一在主配置文件 nginx.conf 中使用 include
指令包含进来。可参考以下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
server {
listen 80;
server_name localhost 192.168.1.174 zh.oc.com;
charset utf-8;
location / {
root "D:\WWW\mycncart";
index index.php index.html index.htm;
autoindex on;
}
location ~ \.php(.*)$ {
root "D:\WWW\mycncart";
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
}
|
1
2
|
# ...
include conf.d/virtual-hosts.conf
|
每一个虚拟主机在 nginx.conf 中都是一个单独的 server{} 块,配置思路也大致相同。
虚拟主机的端口能够监听同一个端口。
server_name
能够是内网IP、域名,公网 IP 和域名,也能够一次性指向多个域名或 IP。
root
指令放在 location
指令在以外相似于全局变量,而每一个 location
块中均可以使用该指令设置的路径。
在于 PHP 关联的时候,要么全局中指定过 root
,不然在 location
中也必须指定根路径,不然重启 Nginx 后也没法找到文件,出现 404 或没法加载网页。