nginx同IP不同端口配置和多域名同IP同80端口配置

写项目时,在配置nginx时需要用到多个IP端口,我总结了下可能会遇到的两个问题(以CentOS系统为例):

1. nginx同IP不同端口对应多个网站配置

这个意思就是如果你有a,b,c三个网站,分别对应3000,4000,5000端口,通过ip + 端口访问不同网站的话,可以配置如下,首先找到/usr/local/nginx/conf/nginx.conf 文件,打开这个配置文件,在文件底部加上这样一句(已有请忽略):

1
include vhost/*.conf;

加入这句的意思是把vhost目录的以.conf结尾的配置文件都加载进来,方便以后新建多个.conf结尾的配置文件,修改后保存nginx.conf文件。
然后在vhost目录李新建a.conf,b.conf,c.conf三个配置文件,下面以a.conf为例:
依旧是打开/usr/local/nginx/conf/nginx.conf 文件,找到默认的server的配置如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
server {
listen 80;
server_name _;
access_log /data/wwwlogs/access_nginx.log combined;
root /home/index;
index index.html index.htm index.php;
#error_page 404 /404.html;
#error_page 502 /502.html;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
location ~ [^/]\.php(/|$) {
#fastcgi_pass remote_php_ip:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
location ~ /\.ht {
deny all;
}
}

复制一份server的配置到a.conf,修改端口指向3000,网站程序路径指向对应目录,比如/home/blog
配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
server {
listen 3000;
server_name _;
access_log /data/wwwlogs/access_nginx.log combined;
root /home/blog;
index index.html index.htm index.php;
#error_page 404 /404.html;
#error_page 502 /502.html;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
location ~ [^/]\.php(/|$) {
#fastcgi_pass remote_php_ip:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
location ~ /\.ht {
deny all;
}
}

b.conf和c.conf配置参照a.conf配置就可以了,配置完保存并允许nginx -s reload重新加载nginx配置就可以了。

2. 多域名同IP同80端口配置

还有一种情况就是你有多个域名比如a.com和b.com,有不想使用域名 + 端口来打开网站,都想使用80端口来打开网站,那么该如何配置呢,这个也比较简单,配置如下:
同样新建a.conf和b.conf,内容如下:

1
2
3
4
5
6
7
server {
listen 80;
server_name a.com;
location / {
proxy_pass http://localhost:3000;
}
}

另一个

1
2
3
4
5
6
7
server {
listen 80;
server_name b.com;
location / {
proxy_pass http://localhost:4000;
}
}

配置完保存并允许nginx -s reload重新加载nginx配置就可以了,这样我们就实现在一台服务器上多域名同IP同80端口的功能了。