nginx 多站点配置方法汇总

发布时间:2020-05-29编辑:脚本学堂
本文介绍实现nginx多站点配置的三种方法,有需要的朋友,可以参考下。

复制代码 代码示例:
user nginx;
worker_processes 1;
# main server error log
error_log /var/log/nginx/error.log ;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
# main server config
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"';
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
server {
listen 80;
server_name _;
access_log /var/log/nginx/access.log main;
server_name_in_redirect off;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
# 包含所有的虚拟主机的配置文件
include /usr/local/etc/nginx/vhosts/*;
}

5、重启 Nginx

方法三

一个服务器上需要跑多个网站,如果仅仅把域名解析到server的IP是不行的,访问不同域名打开的都是nginx默认的网站。要想分别对应,需要在nginx里设置vhost。

用lnmp一键安装包(http://www.lnmp.org)安装的nginx+mysql+php环境,对于其他自己编译的nginx估计配置文件和安装目录会有所不同,自己酌情修改哦,呵呵
编辑/usr/local/nginx/conf/nginx.conf,去掉server的参数。
 

复制代码 代码示例:

server
{
listen 80;
server_name www.jb200.com;
index index.html index.htm index.php;
root /tmp/wwwroot;
location ~ .*.(php|php5)?$
{
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
} copyright
location /status {
stub_status on;
access_log off;
}
copyright
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}

location ~ .*.(js|css)?$
{
expires 12h;
}

log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
access_log /home/wwwroot/logs/access.log access;
}

然后加入vhost定义:
 

复制代码 代码示例:
include /usr/local/nginx/vhost/*.conf;
}
 

再在/usr/local/nginx/建立vhost文件夹,里面创建各域名的对应配置文件。
这个简单,就把之前的server配置内容复制到创建的对应conf文件里就OK了。
 

复制代码 代码示例:

server
{
listen 80;
server_name www.jb200.com;
server_name jb200.com;
index index.html index.htm index.php;
root /tmp/wwwroot/meituge;

location ~ .*.(php|php5)?$
{
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
} copyright
location /status {
stub_status on;
access_log off;
}
copyright

location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
copyright

location ~ .*.(js|css)?$
{
expires 12h;
}
#log_format access '$remote_addr - $remote_user [$time_local] "$request" '
#'$status $body_bytes_sent "$http_referer" '
#'"$http_user_agent" $http_x_forwarded_for';
#access_log /var/www/logs/access.log access;
}

注意:如果使用一级域名,需要在server配置里指定不加www前缀的域名,否则访问jb200.com会被定义到默认站点而非www.jb200.com。
定义如下:
 

复制代码 代码示例:
server_name www.jb200.com;
server_name jb200.com;
 

不然的话,会被一些莫名的问题搞的很头疼的。